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

  1. 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

    1. 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.
    2. Live status: answer "is this employee currently clocked in?" for the employee and their manager.
    3. Worked duration: pair punches into shifts, subtract unpaid breaks, and compute worked hours per day, workweek, and pay period.
    4. 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.
    5. Audited manager corrections: let managers fix missing or mistaken punches with a required reason, preserving the original history.
    6. 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).
  2. 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 time
    

    Three takeaways from the math:

    1. 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!
    2. 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.
    3. Correctness traps (duplicate retries, daylight-saving shifts, out-of-order offline uploads, and post-payday edits) are the hardest engineering problems.
  3. 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 status
    
  4. Data 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) and received_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_York that encodes historical and future daylight-saving rules, unlike a fixed -05:00 offset).
    • Integer cents, never floating-point numbers: binary floats cannot represent $0.10 exactly (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.
  5. 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)
    
  6. 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:

    1. 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.
    2. Per-employee row lock: every employee gets an initial employee_status row (state = 'OUT') at onboarding (with an ON CONFLICT DO NOTHING safeguard for synced employees) so SELECT ... FOR UPDATE always locks a real row. Because the lock is scoped to one employee_id, 3,000 different workers punching at 08:00:00 never block one another!
    3. 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 outbox table 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_utc as event_time_utc, because users can manually change phone or laptop clocks.
    • Managed site kiosks: trust the kiosk's NTP-synced device_time_utc because 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 if device_seq has a gap), punches are saved as flagged and 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); derived shifts and daily_totals are eventually consistent within a few seconds; payroll runs only on an immutable, locked snapshot.

  7. 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 by event_time_utc, and pairs IN -> 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, problems
    

    2. 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 versioned rule_sets data tested by golden test suites, and compute money using exact Decimal math 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 an adjustments row onto the next open pay period (or an off-cycle check if required by local labor law).

  8. 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.

    1. 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_at bookmark — querying updated_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.
    2. 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 + outbox path used by kiosks. Advance the connector's watermark only after the database transaction commits.
    3. 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 block pay_periods/lock for any site whose reconciliation check is red unless a payroll admin logs an explicit waiver.
  9. 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 by employee_id and return 202 Accepted immediately. 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_id primary key makes retries return the original result.
    PostgreSQL primary crash Write errors on 1 of N shards Automatic failover to synchronous standby (0 committed punches lost); other N - 1 shards unaffected; kiosks buffer briefly.
    Kafka or outbox relay down Derived timesheets lag Raw punches stay safe in PostgreSQL; outbox relay catches up; payroll lock verifies outbox + consumer lag == 0 before snapshotting.
    External sync stalls or bad wage rule ships Underpaid or miscalculated checks Daily reconciliation blocks lock on stalled syncs; rule fix creates a new rule_set version, diffs against exported pay_results, and emits auditable adjustments.

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):

  1. 08:00 Eastern (13:00 UTC): Alice taps IN at 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.
  2. 16:30 Eastern (21:30 UTC): the kiosk's Wi-Fi drops, so Alice's OUT punch (event_id = "e2", device_time_utc = 21:30Z) is saved locally on the kiosk and uploaded at 22:15Z. Because we pair shifts using event_time_utc rather than server arrival time, Shift Builder computes 21:30Z - 13:00Z = 8.5 hours (30,600 seconds).
  3. End of biweekly period: suppose Alice has 45.5 approved hours (163,800 seconds) in Week 1. Payroll locks the period and computes 40h x $20.00 + 5.5h x $30.00 = 96,500 cents ($965.00) into an immutable pay_results row.
  4. Post-payday fix: if Alice's manager later adds 30 missed minutes (1,800 seconds) to Week 1, the exported $965.00 row stays untouched and the system writes a +$15.00 (1,500 cents) adjustments row onto the next pay period.

Key trade-offs

  • Synchronous DB state check vs. log-first ingestion. Updating punch_events, locking the worker's employee_status row (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 IN punch keeps database state tidy, but if a worker forgot to clock out yesterday, rejecting today's IN blocks them at the turnstile and discards proof they showed up. Saving every punch and marking anomalies flagged creates 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 adjustments on 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_id on 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 by hash(employee_id).
  • Forgetting to pre-create employee_status before SELECT ... FOR UPDATE. On an employee's very first punch, SELECT ... FOR UPDATE locks zero rows if no status row exists yet, allowing two concurrent first punches to race; insert a default 'OUT' row at onboarding (or INSERT ... ON CONFLICT DO NOTHING first).
  • Subtracting local wall-clock times instead of UTC instants. Subtracting 06:00 - 22:00 reports 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 as America/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 COMMIT but before kafka.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_results row, and writes the positive difference into adjustments linked 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 if branches to ingestion or shift pairing; instead, payroll publishes a new versioned rule_set record with effective_from set 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

Similar questions

More Carvana interview questions

All 3 Carvana questions →