Design a Time-Tracking and Wage Calculation Backend
System DesignModel answerLast updated
Build a backend that records employee time punches, computes hours worked per pay cycle, calculates wages, and handles burst traffic and external data feeds.
You're building the backend for a workforce time-tracking and wage calculation platform.
The system must support:
- Recording employee time punches (clock in, clock out, break start, break end) from various sources: physical kiosks, mobile apps, web portals, and offline devices that sync later
- Calculating total hours worked for each employee within a pay cycle
- Computing gross wages based on hours worked, hourly rates, overtime rules, shift premiums, and holiday pay
- Managing bursts of concurrent punch submissions (e.g., shift changes when hundreds of employees clock in simultaneously)
- Ingesting time records from external systems or legacy databases without creating duplicates
Your design should address:
- API design: What endpoints do you expose, and what guarantees do they provide?
- Data modeling: How do you store time punches, shifts, wage rules, and payroll outputs?
- Architecture: What components do you need, and how do they interact?
- Consistency and correctness: How do you prevent lost or duplicate punches? How do you ensure payroll results are auditable and reproducible?
- Scalability: How does your system handle 10,000+ writes per second during peak times?
- Integration: How do you safely import records from external sources?
Discuss trade-offs, failure modes, and optimization strategies.
Hints
Hint 1
Think about idempotency: how can clients safely retry punch submissions without creating duplicates?
Hint 2
Separate the real-time punch ingestion path from the batch payroll computation path — they have different consistency and latency needs.
Hint 3
Consider using an event log or message queue to absorb traffic spikes and decouple write acknowledgment from downstream processing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarify Scope and Scale
Start by establishing functional and non-functional requirements.
Functional:
- Accept time punches from multiple sources, including offline devices that upload batches later
- Pair punches into shifts and detect anomalies (missing clock-out, duplicate clock-in)
- Calculate worked time per pay period, applying overtime thresholds, break deductions, and rounding rules
- Support manager corrections with full audit history
- Import records from external systems without double-counting
Non-functional:
- Durability over latency: no lost punches
- Idempotent writes to handle retries safely
- Deterministic, auditable payroll calculations
- Handle burst traffic: 10,000 writes/sec during shift changes
Scale estimate:
- 200,000 employees × 4 punches/day = 800k events/day
- Peak load during shift start: ~10k writes/sec
- Annual storage: ~300 bytes/event × 300M events ≈ 90 GB/year
Storage is cheap; handling bursts and ensuring correctness are the challenges.
API Design
POST /v1/punches
Headers: Idempotency-Key: <client-generated-uuid>
Body: {
employee_id,
type: "IN" | "OUT" | "BREAK_START" | "BREAK_END",
device_time_utc,
device_id,
location,
source: "KIOSK" | "MOBILE" | "IMPORT"
}
Response: 202 Accepted { punch_id, status: "ACCEPTED" }
GET /v1/employees/{id}/current-status
-> { status: "ON_SHIFT" | "ON_BREAK" | "OFF", last_punch_time }
GET /v1/employees/{id}/timesheet?pay_period=2026-11-01
-> { shifts: [...], total_hours, total_overtime }
POST /v1/punches/{id}/corrections
Body: { corrected_time, reason, manager_id }
POST /v1/pay-periods/{id}/finalize
-> locks the period and triggers payroll calculation
GET /v1/pay-periods/{id}/wages/{employee_id}
-> { regular_hours, overtime_hours, gross_pay_cents, breakdown }
Key decisions:
- Client-generated idempotency keys allow offline devices to retry safely and enable external imports to use
<source_system>:<external_id>as the key - 202 Accepted once the punch is durably stored; downstream views update asynchronously
- Corrections are new events, never updates; this preserves audit trails
Data Model
punch_events (append-only source of truth, partitioned by employee_id)
| Column | Notes |
|---|---|
| punch_id | UUID primary key |
| employee_id | Partition/shard key |
| idempotency_key | UNIQUE constraint on (employee_id, idempotency_key) |
| type | IN / OUT / BREAK_START / BREAK_END |
| server_time_utc | Authoritative timestamp |
| device_time_utc | Recorded for audit |
| device_id, location | |
| source, source_record_id | For deduplication during imports |
| supersedes_punch_id | NULL unless this is a correction |
shifts (derived materialized view)
| Column | Notes |
|---|---|
| shift_id | |
| employee_id | |
| start_punch_id, end_punch_id | References to punch_events |
| start_time, end_time | |
| break_minutes | |
| status | COMPLETE / MISSING_OUT / ANOMALY |
| employee_timezone | For DST-aware day boundaries |
wage_rules (versioned)
| Column | Notes |
|---|---|
| rule_id, effective_from, effective_to | |
| hourly_rate_cents | Use integers for money |
| daily_overtime_threshold_minutes | |
| weekly_overtime_threshold_minutes | |
| shift_differential_rules | JSON or separate table |
pay_periods
| Column | Notes |
|---|---|
| period_id | |
| start_date, end_date | |
| status | OPEN / LOCKED / PAID |
payroll_results
| Column | Notes |
|---|---|
| employee_id, period_id | |
| regular_minutes, overtime_minutes | |
| gross_pay_cents | Integer arithmetic, no floats |
| wage_rule_version | For reproducibility |
| input_hash | Hash of input shifts for verification |
Never mutate punch_events. Corrections are compensating records. This ensures auditability and makes payroll replayable.
Architecture
Kiosks / Mobile Apps / Web
↓
API Gateway (auth, rate limiting)
↓
Punch Service (stateless, horizontally scaled)
- Validate request
- Check idempotency cache (Redis)
- Publish to Kafka topic "punches" (partitioned by employee_id)
- Return 202 once Kafka acknowledges
↓
Kafka ("punches" topic, partition key = employee_id)
↓
┌─────────┴──────────┬─────────────┐
↓ ↓ ↓
Event Writer Shift Builder Status Cache
(to sharded (state machine, (Redis,
Postgres) builds shifts real-time view)
table)
External System → Sync Ingestor → same Kafka topic (with source metadata)
Scheduled Job → Payroll Engine → payroll_results → External payroll provider
Why Kafka?
- Absorbs burst traffic (10k writes/sec) without overloading downstream consumers
- Provides ordered per-employee event streams (via partition key)
- Enables at-least-once delivery with idempotent consumers
Simpler alternative: Write synchronously to sharded Postgres with unique constraint on idempotency_key. At 10k writes/sec across 8 shards, this is feasible but less resilient to downstream consumer slowdowns. Choose based on team familiarity and operational complexity tolerance.
Key Design Deep-Dives
Idempotency and Deduplication
- Unique constraint on
(employee_id, idempotency_key)is the final safeguard - Punch Service checks Redis cache before publishing to Kafka for fast duplicate rejection
- External imports use
<source_system>:<external_record_id>as idempotency key
Handling Burst Traffic
- Kafka buffers messages; consumers drain at sustainable rate
- Punch Service scales horizontally behind load balancer
- Redis idempotency cache is sharded by employee_id
Consistency Guarantees
- Real-time status view: Eventually consistent (typically <500ms lag)
- Payroll calculation: Strongly consistent at period finalization:
- Lock the period
- Wait until Kafka consumer lag = 0 for events up to period end + grace window
- Snapshot shifts table and run payroll engine
Timestamp Handling
- Trust server time for online punches
- Accept device time for offline uploads only if within bounds (not future, not >24 hours old)
- Store both server and device timestamps
- Compute durations in UTC; apply overtime day/week boundaries in employee's local timezone (DST-aware)
Anomaly Detection
- Don't reject malformed sequences (double clock-in, clock-out without clock-in) at write time — offline/imported punches may arrive out of order
- Accept the punch, then mark the shift with status ANOMALY or MISSING_OUT
- Surface anomalies to managers before period finalization
- Optionally auto-close open shifts after threshold (e.g., 16 hours), flagged for review
Payroll Computation
- Pure function:
calculate_wages(shifts, wage_rules) → result - Use integer minutes and integer cents throughout
- Apply rounding (e.g., nearest 6 minutes if policy allows)
- Apply overtime tiers in sequence: daily OT, then weekly OT
- Store
input_hashandrule_versionfor reproducibility - Corrections after period is LOCKED create adjustment records in next period; never mutate finalized payroll
Failure Handling
- Kafka: Replication factor 3,
acks=all - Postgres: Replicas with synchronous replication for critical tables
- Consumers: At-least-once delivery + idempotent upserts
- Monitor consumer lag and alert on anomalies or stalls
Common Mistakes
- Using floats for money (rounding errors accumulate)
- Updating punch records in place (loses audit trail)
- Rejecting anomalous punches at write time (breaks offline sync)
- Ignoring timezones or DST when computing daily overtime
- Not providing idempotency guarantees (causes duplicate pay)
Optimization Strategies
If scale increases 10×:
- Shard Postgres by employee_id ranges
- Use read replicas for timesheet queries
- Cache frequently accessed data (current status, recent shifts) in Redis
- Batch-process payroll per employee in parallel using worker pool
- Consider CQRS: separate write model (event log) from read models (shifts, status)
Complexity: O(n) writes where n = number of punches; O(m) payroll computation where m = number of shifts per period per employee (typically small constant).