Workforce Time-Tracking and Payroll Backend Design
Easy · System Design · Software Engineer · Onsite
Prompt
Architect the backend platform for an enterprise workforce timekeeping and gross-compensation service used by hourly staff across distributed operating sites.
The platform must support five core capabilities:
- Shift punches: Capture employee clock-in and clock-out events reliably across site terminals and client apps.
- Payable time aggregation: Pair raw punches into shifts and compute each worker's net worked time over a recurring pay cycle.
- Rule-driven gross pay: Calculate gross earnings from worked hours and configurable compensation policies (such as base hourly rates, shift differentials, and overtime tiers).
- Shift-handover surge handling: Sustain low write latency during sharp request spikes when large shifts start and end on the hour.
- External source integration: Ingest and reconcile attendance events originating from external databases or third-party time-clock systems.
Scope & Expectations
- APIs, schema, and architecture: Define external endpoints, an auditable relational data model, and a service layout separating real-time punch capture from asynchronous shift building and batch payroll execution.
- Consistency and payroll accuracy: Explain client idempotency, per-employee state locking, UTC vs. local time-zone / daylight-saving arithmetic, and immutable pay-period snapshots with forward adjustments.
- External sync, resilience, and high-scale tuning: Cover connector patterns and automated reconciliation checks, offline/degraded failure handling, and concrete optimizations if shift-change write volume grows tenfold.
Step-by-step walkthrough
Clarify requirements
"Attendance" and "payroll" can each grow into an entire enterprise product, so start by drawing crisp boundaries around what our backend computes versus what belongs to downstream tax/banking providers.
Functional requirements
- Clock in, clock out, and breaks: accept punches (
IN,OUT,BREAK_START,BREAK_END) from physical site kiosks (badge or PIN), a mobile app, and a web portal. - Live status: answer "is this employee currently clocked in?" for the employee and their manager.
- Worked duration: pair punches into shifts, subtract unpaid breaks, and compute worked hours per day, workweek, and pay period.
- Gross pay calculation: apply versioned wage rules (hourly base rates, overtime multipliers, night-shift differentials, holiday pay) to compute gross pay, then export approved hours and gross amounts to an external payroll/tax processor.
- Audited manager corrections: let managers fix missing or mistaken punches with a required reason, preserving the original history.
- External synchronization: ingest and reconcile attendance records from external databases, partner APIs, or legacy badge systems.
Non-functional requirements
- Zero lost punches: once the service confirms a punch, it must never vanish — losing a punch means unpaid labor, legal liability, and broken employee trust.
- Idempotent writes: network retries from flaky Wi-Fi or kiosks must never create duplicate punches or double pay. An idempotency key is a unique ID generated by the client before sending a request so repeating that request produces the exact same single outcome.
- Shift-change burst handling: keep p99 punch latency under 300 ms during sharp top-of-the-hour spikes, and allow site kiosks to keep accepting punches offline.
- Reproducible, auditable pay: running payroll twice on the same locked period and rule version must produce the exact same cent amounts, traceable back to raw punches.
- High availability: 99.9%+ availability on the punch ingestion path; payroll calculation is an asynchronous batch job that can tolerate brief retries.
Scale assumptions to confirm
- Large multi-site employer (for example, nationwide inspection centers, warehouses, and delivery hubs): 1,000,000 hourly employees across 2,000 sites spanning 4 US time zones, paid biweekly (every 14 days).
- Clock in, clock out, and breaks: accept punches (
Back-of-the-envelope numbers
Put concrete numbers behind the traffic shape so you can show why peak bursts and correctness — rather than average throughput — drive the architecture.
Daily punch volume 1,000,000 employees x 70% working on a given day = 700,000 shifts / day 4 punches / shift (IN, BREAK_START, BREAK_END, OUT) = 2,800,000 punches / day Average write rate: 2,800,000 / 86,400 sec = ~32 punches / sec (tiny!) Shift-change burst (the real challenge) Shifts start and end on the hour (e.g., outgoing shift clocks OUT while incoming clocks IN). Suppose 25% of daily clock-ins (175,000) arrive in the 10-minute window before 08:00, and 40% of those (70,000) land in the final 60 seconds: 70,000 / 60 sec = ~1,170 clock-ins/sec (+ overlapping clock-outs -> ~2,000-3,000/sec spikes) Design target: 5,000 punches/sec sustained, with a clean path to 50,000/sec Read traffic & storage Status + timesheet reads at peak: ~2-3x write rate (~6,000-10,000 reads/sec) Event size (~300 bytes incl. indexes): 2.8M x 300 B = ~0.84 GB/day -> ~307 GB/year 7-year legal retention: ~2.1 TB total (fits comfortably on sharded relational storage) Biweekly payroll batch run 1,000,000 employees x ~40 events/period = 40,000,000 punch rows read ~1 ms rule evaluation per employee = 1,000 CPU-seconds (~17 core-minutes) Across 32 worker threads/pods = ~32 seconds wall-clock timeThree takeaways from the math:
- Peak-to-average ratio is nearly 100x (~3,000/s vs. ~32/s), and US time zones are separated by whole hours — meaning 09:00 Eastern, 08:00 Central, and 07:00 Mountain shift handovers fire at the exact same UTC second!
- Storage and batch compute are modest (~2 TB over 7 years; under a minute for payroll compute), so we should choose a relational database with rock-solid transactions rather than sacrificing consistency.
- Correctness traps (duplicate retries, daylight-saving shifts, out-of-order offline uploads, and post-payday edits) are the hardest engineering problems.
API design
Design around append-only events — records that are only ever inserted, never overwritten — so every punch and manager edit leaves a permanent audit trail.
1. Punching (employee devices & site kiosks) POST /v1/punches Body: { "event_id": "uuid-created-on-device-at-tap-time", "employee_id": "emp_84920", "kind": "IN" | "OUT" | "BREAK_START" | "BREAK_END", "device_time_utc": "2026-11-30T13:58:12Z", "device_id": "kiosk_phx_04", "device_seq": 10482, "site_id": "site_phx_01", "source": "kiosk" | "mobile" | "web" } Response 201: { "event_id": "...", "accepted_time_utc": "2026-11-30T13:58:12Z", "status": "accepted" | "flagged", "current_state": "IN" | "OUT" | "ON_BREAK", "warning": null | "Flagged: already clocked IN at 13:55Z" } (Retrying the same event_id returns the original 201 response without creating a second row.) POST /v1/punches:batch # Kiosk micro-batches or offline backlog recovery (up to 500 events) GET /v1/employees/{id}/status # -> { "state": "IN", "since_utc": "...", "open_shift_id": "..." } 2. Timesheets & manager corrections GET /v1/employees/{id}/timesheet?from=2026-11-16&to=2026-11-29 POST /v1/shifts/{shift_id}/corrections Body: { "new_start_utc": "...", "new_end_utc": "...", "reason": "Forgot badge at lunch", "manager_id": "..." } POST /v1/timesheets/{employee_id}/{period_id}/approve 3. Payroll runs POST /v1/pay-periods/{period_id}/lock # Freeze approved shifts + wage rules POST /v1/pay-periods/{period_id}/runs # Start async calculation -> { "run_id": "..." } GET /v1/pay-periods/{period_id}/runs/{run_id}/results # Itemized regular/OT/differential lines POST /v1/pay-periods/{period_id}/runs/{run_id}/export # Idempotent push to payroll/tax provider 4. External sync POST /v1/sync/{source}/events:bulk GET /v1/sync/{source}/status # Lag, watermark, last reconciliation statusData model
Shard all employee-scoped tables in PostgreSQL by
hash(employee_id)so all punches, live status, and shifts for one person live on the exact same shard, while a 08:00 shift burst spreads evenly across all shards.Reference & rule tables (replicated / cached in memory) employees (employee_id PK, site_id, home_tz, pay_group, job_codes[], status) wage_rates (employee_id, job_code, rate_cents_per_hour, effective_from, effective_to) rule_sets (rule_set_id, version, rules_json, effective_from) Write-path tables (sharded by hash(employee_id)) punch_events (event_id PK, employee_id, kind, event_time_utc, device_time_utc, received_at_utc, source, source_ref, device_id, site_id, status: accepted|flagged|void, supersedes_event_id, created_by, reason) employee_status (employee_id PK, state: OUT|IN|ON_BREAK, last_event_id, last_event_time_utc, version) outbox (outbox_id PK, employee_id, payload_json, created_at_utc, published_at_utc) Derived attendance & immutable payroll tables shifts (shift_id PK, employee_id, start_event_id, end_event_id, start_utc, end_utc, local_work_date, worked_seconds, unpaid_break_seconds, flags[], approval_state) daily_totals (employee_id, local_work_date, worked_seconds, PRIMARY KEY (employee_id, local_work_date)) pay_periods (period_id PK, pay_group, start_date, end_date, state: open|grace|locked|calculated|approved|exported) pay_runs (run_id PK, period_id, rule_set_version, started_at_utc, state) pay_results (run_id, employee_id, input_hash, line_items_json, gross_cents, PRIMARY KEY (run_id, employee_id)) adjustments (adj_id PK, employee_id, target_period_id, origin_period_id, delta_cents, reason) sync_sources (source PK, mode: cdc|pull|file, watermark, last_reconciled_date, status) id_mappings (source, external_employee_id, employee_id, PRIMARY KEY (source, external_employee_id))Key data-modeling decisions:
- Store two timestamps on every punch:
event_time_utc(when the worker actually punched) andreceived_at_utc(when our server received it). Offline kiosk batches can arrive hours late; storing both places the shift at the real work time while exposing upload lag and clock drift. - UTC instants + IANA time zone names: store timestamps in UTC and the site's IANA time zone (a region identifier like
America/New_Yorkthat encodes historical and future daylight-saving rules, unlike a fixed-05:00offset). - Integer cents, never floating-point numbers: binary floats cannot represent
$0.10exactly (0.1 + 0.2 != 0.3), so store rates and totals in integer cents (2000=$20.00) and compute intermediate hours with exact decimal arithmetic.
- Store two timestamps on every punch:
High-level architecture
Separate the low-latency punch write path from asynchronous shift pairing, external sync, and batch payroll calculation:
Site Kiosks Mobile / Web Apps External DB / Legacy API / SFTP CSV (local SQLite (live network) | queue + NTP) | v | | Sync Connectors (CDC / watermark pull / file) +---------+---------+ (map IDs, attach deterministic event_id) | | v v API Gateway & Load Balancer | (auth, device rate limits) | | | v | Punch Ingestion Service (stateless, pre-scaled) <---+ | | Single-shard ACID transaction: | insert punch_events + update employee_status + insert outbox v PostgreSQL Shards (by hash(employee_id); sync standby + read replicas) | v Outbox Relay ---> Kafka (partitioned by employee_id) | | | v v v Shift Builder Anomaly Detector Data Warehouse (pair IN/OUT, (16h+ open shift, (BI & daily sync update totals) clock skew, geo) reconciliation) | v Manager Timesheet UI (fix flags, approve shifts) | v Payroll Engine (lock snapshot -> parallel workers -> immutable pay_results)Deep dive: the punch write path and consistency guarantees
The write path must guarantee that retries never double-punch, concurrent requests for one employee never corrupt their state, and downstream Kafka consumers never miss a committed punch.
We combine three mechanisms inside one single-shard database transaction:
- Idempotent insert via client
event_id:INSERT ... ON CONFLICT (event_id) DO NOTHING. If zero rows are inserted, this request is a network retry, so we read and return the existing result. - Per-employee row lock: every employee gets an initial
employee_statusrow (state = 'OUT') at onboarding (with anON CONFLICT DO NOTHINGsafeguard for synced employees) soSELECT ... FOR UPDATEalways locks a real row. Because the lock is scoped to oneemployee_id, 3,000 different workers punching at 08:00:00 never block one another! - Transactional outbox: writing to PostgreSQL and then publishing to Kafka in application code is a "dual write" — if the server crashes in between, the database has the punch but Shift Builder never hears about it. A transactional outbox writes the outgoing event into an
outboxtable inside the same database transaction; a background relay process then publishes uncommitted outbox rows to Kafka at least once.
BEGIN; -- 1. Deduplicate retries using the device-generated UUID. INSERT INTO punch_events ( event_id, employee_id, kind, event_time_utc, device_time_utc, received_at_utc, source, device_id, site_id, status ) VALUES ( :event_id, :emp_id, :kind, :event_time_utc, :device_time_utc, NOW(), :source, :device_id, :site_id, 'accepted' ) ON CONFLICT (event_id) DO NOTHING RETURNING event_id; -- If no row is returned here, commit/rollback and return the stored response for :event_id. -- 2. Ensure a status row exists, then lock ONLY this employee's row. INSERT INTO employee_status (employee_id, state, last_event_time_utc, version) VALUES (:emp_id, 'OUT', '1970-01-01T00:00:00Z', 0) ON CONFLICT (employee_id) DO NOTHING; SELECT state, last_event_time_utc FROM employee_status WHERE employee_id = :emp_id FOR UPDATE; -- 3. In application logic: -- - If :event_time_utc < last_event_time_utc, this is an older offline kiosk punch arriving late: -- keep punch_events intact, leave current employee_status unchanged, and let Shift Builder re-pair. -- - If the transition is invalid (e.g., IN when already IN), NEVER drop the punch! -- Mark punch_events.status = 'flagged' for manager review so proof of work is never lost. -- - Otherwise update employee_status to the new state and :event_time_utc. -- 4. Queue downstream notification atomically in the same transaction. INSERT INTO outbox (outbox_id, employee_id, payload_json, created_at_utc) VALUES (:outbox_id, :emp_id, :event_json, NOW()); COMMIT;Which clock can we trust?
- Mobile and web: trust the server's
received_at_utcasevent_time_utc, because users can manually change phone or laptop clocks. - Managed site kiosks: trust the kiosk's NTP-synced
device_time_utcbecause an offline kiosk may upload punches an hour later. Every batch includes the kiosk's current clock reading so the server measures clock skew; if skew exceeds 2 minutes (or ifdevice_seqhas a gap), punches are saved asflaggedand Ops is alerted.
Consistency summary: confirmed punches are durable (committed to primary + synchronous standby before HTTP
201); single-employee status reads are linearizable (every read sees the latest completed write in real-time order when routed to the shard primary); derivedshiftsanddaily_totalsare eventually consistent within a few seconds; payroll runs only on an immutable, locked snapshot.- Idempotent insert via client
Deep dive: pairing shifts, daylight saving, and wage calculation
1. Pairing punches without guessing. When Kafka delivers a punch for
employee_id, Shift Builder loads that employee's non-void punches for the affected local day (plus adjacent days for overnight shifts), sorts them byevent_time_utc, and pairsIN -> OUT. If someone forgot to clock out, never invent a clock-out timestamp — guessing either steals wages or overpays. Emit an anomaly flag so the manager fixes it before payroll locks.def pair_punches(events): """Pair time-sorted (timestamp_utc, kind) events into completed shifts and anomaly flags.""" shifts = [] problems = [] open_start = None for ts_utc, kind in events: if kind == "IN": # A second IN before an OUT means the previous shift is missing its clock-out. if open_start is not None: problems.append(("missing_out", open_start)) open_start = ts_utc elif kind == "OUT": if open_start is None: problems.append(("missing_in", ts_utc)) else: shifts.append((open_start, ts_utc)) open_start = None if open_start is not None: problems.append(("still_open", open_start)) return shifts, problems2. Daylight-saving time (DST) correctness. Always subtract UTC instants to get worked duration, and use the site's IANA time zone only to assign the shift to a local work date and workweek (for example, using the local date when the shift started):
Night shift scheduled 22:00 -> 06:00 in America/New_York: Fall-back night (Sat Oct 31 -> Sun Nov 1, 2026): 22:00 EDT (02:00 UTC) to 06:00 EST (11:00 UTC) = 9 actual hours worked! Spring-forward night (Sat Mar 7 -> Sun Mar 8, 2026): 22:00 EST (03:00 UTC) to 06:00 EDT (10:00 UTC) = 7 actual hours worked! Naive wall-clock subtraction (06:00 - 22:00 mod 24) says "8 hours" on BOTH nights -> illegal!3. Exact decimal wage rules and frozen pay runs. Wage rules vary by jurisdiction and contract: job-specific base rates, mid-period raises (
effective_from), night differentials, holiday multipliers, and overtime (for example, US federal FLSA requires 1.5x the weighted regular rate — including shift differentials — for hours over 40 in a workweek, while states like California add daily overtime over 8 and 12 hours). Keep HR/legal rules in versionedrule_setsdata tested by golden test suites, and compute money using exactDecimalmath rounded once to integer cents:from decimal import Decimal, ROUND_HALF_UP def weekly_pay_cents( worked_seconds: int, rate_cents_per_hour: int, threshold_hours: int = 40, ot_multiplier: Decimal = Decimal("1.5"), ) -> int: """Compute gross weekly pay in integer cents using exact decimal math.""" regular_limit_seconds = threshold_hours * 3600 regular_seconds = min(worked_seconds, regular_limit_seconds) overtime_seconds = worked_seconds - regular_seconds rate = Decimal(rate_cents_per_hour) exact_cents = ( Decimal(regular_seconds) * rate + Decimal(overtime_seconds) * rate * ot_multiplier ) / Decimal(3600) # Round once at the end to the nearest cent (45.5h at $20.00/h -> 96500 cents = $965.00). return int(exact_cents.quantize(Decimal("1"), rounding=ROUND_HALF_UP))4. The payroll state machine (freeze, compute, adjust forward):
open (14 days) -> grace window (48h for offline kiosks + manager fixes/approvals) -> locked (snapshot approved shifts + wage_rates + rule_set_version + input_hash) -> calculated (32 parallel workers write immutable pay_results) -> reviewed & exported (push batch with idempotent run_id to payroll provider)If a manager fixes a forgotten punch after a pay period is exported, never mutate the exported
pay_results. Recompute what that period should have paid, take the difference (delta_cents), and insert anadjustmentsrow onto the next open pay period (or an off-cycle check if required by local labor law).Deep dive: synchronizing external attendance systems
Large employers frequently acquire companies or run legacy badge databases at older sites. External synchronization must feed our single source of truth without silent drops or duplicate hours.
- Pick the right connector per external source:
- Direct database access: use Change Data Capture (CDC) — reading the external database's internal transaction log (via a tool like Debezium) to stream inserts and updates in order with seconds of lag.
- Vendor REST API: poll incrementally using a watermark — a saved
updated_atbookmark — queryingupdated_at >= watermark - 5 minutes. The 5-minute overlap window catches slightly delayed transactions in the vendor DB, and our idempotent key discards duplicates. - Nightly SFTP CSV drops: hash
(source, file_checksum, row_number)as the deterministic key so re-uploading a file is a safe no-op.
- Route through one canonical ingestion pipeline: map external worker IDs via
id_mappings(parking unknown IDs in a dead-letter queue (DLQ) — a holding queue for unmappable records so one bad row never stalls the pipeline), attach deterministic key(source, source_record_id, source_version), and feed the exact same validation +punch_events+outboxpath used by kiosks. Advance the connector's watermark only after the database transaction commits. - Gate payroll lock on automated daily reconciliation: a stalled external sync connector looks identical to "nobody worked today." Run a daily reconciliation job comparing
(employee_count, punch_count, total_worked_minutes)per synced site between the external source and our database, and blockpay_periods/lockfor any site whose reconciliation check is red unless a payroll admin logs an explicit waiver.
- Pick the right connector per external source:
Scaling, high-traffic optimizations, and failure handling
Scaling from 5,000 punches/s to 50,000+ punches/s
- Scheduled pre-scaling + kiosk jitter: shift starts (
07:00,08:00,16:00) are completely predictable, so scale Punch Ingestion pods 15 minutes before the hour rather than reacting to lagging CPU metrics, and pause low-priority bulk sync jobs during those 15-minute windows. Have kiosks confirm locally in < 50 ms and flush micro-batches every 2–5 seconds with random jitter, collapsing 50 workers in a break-room line into 2–3 batch HTTP calls. - Avoid time-based hot partitions: never partition tables or Kafka topics by timestamp or minute (which routes every 08:00 punch to a single hot node); always partition by
hash(employee_id). Keep timesheet reads on read replicas and analytics on the warehouse so shard primaries only handle punches and status locks. - Extreme traffic optimization (50,000+ punches/s — log-first ingestion): if synchronous single-row SQL transactions ever become the bottleneck, switch the API to append validated punches directly to a durable, replicated Kafka topic (
acks=all,min.insync.replicas=2) partitioned byemployee_idand return202 Acceptedimmediately. Stream consumers then batch-insert 500 punches per SQL transaction (cutting database transaction overhead ~100x) and run the per-employee state machine in partition order. Trade-off:"already clocked in"warnings become asynchronous push notifications rather than inline HTTP fields.
Failure handling summary
Failure scenario Impact if unhandled Mitigation Site internet outage Workers cannot clock in Kiosk buffers signed punches in local SQLite with monotonic device_seq; flushes with skew/gap checks once back online.Client timeout + retry Duplicate punch / double hours Client-generated event_idprimary key makes retries return the original result.PostgreSQL primary crash Write errors on 1 of N shards Automatic failover to synchronous standby ( 0committed punches lost); otherN - 1shards unaffected; kiosks buffer briefly.Kafka or outbox relay down Derived timesheets lag Raw punches stay safe in PostgreSQL; outboxrelay catches up; payrolllockverifies outbox + consumer lag == 0 before snapshotting.External sync stalls or bad wage rule ships Underpaid or miscalculated checks Daily reconciliation blocks lockon stalled syncs; rule fix creates a newrule_setversion, diffs against exportedpay_results, and emits auditableadjustments.- Scheduled pre-scaling + kiosk jitter: shift starts (
Intuition & how it works
Think of an attendance and payroll backend as a tamper-evident receipt box paired with a frozen bank statement. Every time an employee taps a badge at a break-room kiosk, the kiosk creates a uniquely numbered slip (event_id) and drops it into an append-only log — a table where records are only ever added, never erased or overwritten. If a manager later fixes a forgotten clock-out, they do not erase the original slip; they drop in a signed correction slip that points to it. At the end of the two-week pay period, payroll waits for pending fixes, freezes a read-only snapshot of approved shifts and wage rules, and computes paychecks in exact integer cents from that snapshot.
A naive system simply updates a mutable hours_worked counter using local wall-clock times whenever someone taps "Clock Out." That breaks down quickly in production: a mobile retry over spotty Wi-Fi clocks the worker out twice, an overnight shift across daylight-saving time overpays or underpays by a full hour, an offline warehouse kiosk either blocks workers from starting their shift or uploads punches out of order, and editing a past timesheet silently changes an already-paid period without leaving an audit trail.
Trace four concrete events for one worker, Alice (rate = 2000 cents/h = $20.00/h):
- 08:00 Eastern (
13:00 UTC): Alice tapsINat a kiosk (event_id = "e1"). The kiosk times out and retries"e1"; PostgreSQL sees"e1"already exists (ON CONFLICT DO NOTHING) and returns the original success without creating a duplicate punch. - 16:30 Eastern (
21:30 UTC): the kiosk's Wi-Fi drops, so Alice'sOUTpunch (event_id = "e2",device_time_utc = 21:30Z) is saved locally on the kiosk and uploaded at22:15Z. Because we pair shifts usingevent_time_utcrather than server arrival time, Shift Builder computes21:30Z - 13:00Z = 8.5 hours(30,600seconds). - End of biweekly period: suppose Alice has
45.5approved hours (163,800seconds) in Week 1. Payroll locks the period and computes40h x $20.00 + 5.5h x $30.00 = 96,500 cents ($965.00)into an immutablepay_resultsrow. - Post-payday fix: if Alice's manager later adds 30 missed minutes (
1,800seconds) to Week 1, the exported$965.00row stays untouched and the system writes a+$15.00(1,500cents)adjustmentsrow onto the next pay period.
Key trade-offs
- Synchronous DB state check vs. log-first ingestion. Updating
punch_events, locking the worker'semployee_statusrow (SELECT ... FOR UPDATE), and writing to a transactional outbox (a table in the same database transaction used to reliably relay events to Kafka) gives immediate"already clocked in"warnings and easily handles ~5,000 punches/s across sharded PostgreSQL. At 50,000+ punches/s, appending directly to replicated Kafka first and batch-writing to PostgreSQL cuts DB load ~100x, at the cost of making state warnings asynchronous. - Flagging vs. rejecting invalid punch sequences. Rejecting a second
INpunch keeps database state tidy, but if a worker forgot to clock out yesterday, rejecting today'sINblocks them at the turnstile and discards proof they showed up. Saving every punch and marking anomaliesflaggedcreates manager review work, which is far cheaper than lost-wage disputes. - Append-only punch events vs. mutable shift rows. Storing raw immutable events plus superseding corrections uses slightly more storage and requires a background Shift Builder to pair shifts, but it lets late offline uploads slot cleanly into the timeline and preserves the full legal audit history.
- Strong consistency on punches and snapshots vs. eventual consistency on dashboards. Confirmed punches and per-employee status use single-shard ACID transactions (linearizable per employee — reads always see the latest completed write in real-time order), while manager timesheet totals update asynchronously via Kafka within a few seconds so the punch write path stays fast.
- Frozen pay periods + forward adjustments vs. live recalculation. Locking a pay period before computing pay means late edits must ride as
adjustmentson the next paycheck (or an off-cycle check), but it guarantees exported bank files never drift out of sync with stored payroll records. - External sync via CDC vs. watermark polling vs. file drops. Change Data Capture (CDC) (streaming changes from the external database's transaction log) gives near-zero lag when DB access exists; watermark polling (
updated_at >= watermark - 5 min, where a watermark is the last committed timestamp bookmark) works over any vendor API with idempotent deduplication; nightly CSV files are simplest but highest-latency. Regardless of transport, automated daily reconciliation against source counts/minutes is required to catch silent stalls.
Common mistakes
- Generating
event_idon the server instead of the client device. If the server invents the ID upon receipt, every client retry after a network timeout inserts a brand-new duplicate punch. - Partitioning tables or Kafka topics by timestamp or minute. Shift changes happen on the hour across time zones (
09:00 Eastern == 08:00 Central == 14:00 UTC), so time-based keys funnel the entire 100x burst onto one hot partition instead of spreading it byhash(employee_id). - Forgetting to pre-create
employee_statusbeforeSELECT ... FOR UPDATE. On an employee's very first punch,SELECT ... FOR UPDATElocks zero rows if no status row exists yet, allowing two concurrent first punches to race; insert a default'OUT'row at onboarding (orINSERT ... ON CONFLICT DO NOTHINGfirst). - Subtracting local wall-clock times instead of UTC instants. Subtracting
06:00 - 22:00reports 8 hours on both the 9-hour fall-back night and the 7-hour spring-forward night. Compute elapsed seconds in UTC and use the site's IANA time zone (such asAmerica/Chicago) only to determine which work date/week owns the shift. - Using floating-point types (
float/DOUBLE) for hours or currency. Rounding drift across thousands of employees causes penny mismatches; store integer cents and use exact decimal math rounded once per documented rule. - Auto-closing missing clock-outs or editing exported pay runs. Guessing an 8-hour shift invents or erases payable time, and overwriting an already-exported pay run breaks reconciliation with tax and direct-deposit systems.
- Dual-writing to PostgreSQL and Kafka without an outbox. If the API process crashes after
COMMITbut beforekafka.send(), the punch exists in SQL while Shift Builder never computes the shift.
Follow-up questions
- How should the platform handle a paycheck dispute when a missing punch is discovered after payroll has already been exported? Their manager submits a reasoned correction event that adds the missing punch and obtains normal approval, without modifying the already-exported pay period. Payroll runs a deterministic recalculation of that closed period with the updated shifts, compares the new total against the immutable
pay_resultsrow, and writes the positive difference intoadjustmentslinked to both the origin period and the next open period. If state labor law requires immediate payment rather than waiting for the next biweekly cycle, payroll triggers an off-cycle export for just that adjustment row. - What technical controls help deter and detect buddy punching, where one worker clocks in on behalf of an absent colleague? Enforce identity at capture time: site kiosks require badge tap plus PIN (or capture a quick badge-in photo for audit), while mobile punches require authenticated device binding plus a GPS geofence check recorded on the event. Downstream on the Kafka stream, an anomaly detector flags suspicious patterns — such as one personal phone punching for multiple
employee_ids, two punches at distant sites minutes apart, or sudden unapproved overtime spikes — routing flags to managers rather than auto-rejecting punches at the door. - If a jurisdiction introduces new daily overtime tiers next month, how do you roll out those wage rules safely? Engineering adds no site-specific
ifbranches to ingestion or shift pairing; instead, payroll publishes a new versionedrule_setrecord witheffective_fromset to the law's start date for pay groups in that state, encoding how daily and weekly overtime buckets interact without double-counting overtime hours. Before go-live, the team validates the rule version against HR/legal golden test cases (including midnight-crossing shifts and pay periods straddling the effective date) and runs a shadow dry-run over the prior two pay periods to inspect employee-level diffs.
Follow-up questions
- How should the platform handle a paycheck dispute when a missing punch is discovered after payroll has already been exported?
- What technical controls help deter and detect buddy punching, where one worker clocks in on behalf of an absent colleague?
- If a jurisdiction introduces new daily overtime tiers next month, how do you roll out those wage rules safely?
Similar questions
- Stakeholder Alignment, AI Workflows, and Plain-Language Communication
- Convert Integer to American English Words
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests