Payroll System
The bank may have accepted a payroll transfer, but the payment worker lost the response.
Topic tools
Layout updated
Problem statement
Design a US payroll service for multiple employers. Each employer can calculate and review a payroll run, approve it, and track whether the resulting payments went through.
Functional requirements
- Calculate how much each employee should be paid.
- Let employers review and approve payroll before sending payments.
- Send approved payments and show which ones have settled or need attention.
Non-functional requirements
- Pay employees the amounts the employer approved. Avoid duplicate payments when a request is retried.
- Handle busy payroll days so one large employer cannot delay everyone else.
- Keep each employer’s payroll data private and retain a record of approvals and payments.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 100,000 companies, 10 million employees, and up to 100,000 employees in one company. |
| 10 million calculations in four hours is about 694/s. Plan for an illustrative 3,000 to 5,000/s burst. |
Entities
| Entity / logical owner |
|---|
| Payroll run and calculation version |
| Approval |
| Payment obligation and attempts |
| Transactional and audit trail |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/v1/companies/{companyId}/payroll-runs | 202 after durable creation. Repeat with the same request key. |
GET/v1/payroll-runs/{runId} | 200 with calculation version, totals, status and exceptions. |
POST/v1/payroll-runs/{runId}/approve | 200 for a matching version and totals. Return 409 if the reviewed version is stale. |
High-level design
How to draw this design
- Start and Payroll , orchestrator, HR, and time data
- Calculate and approveKafka calculation work, tax engine, workers, and review
- Create and send paymentsPostgreSQL, , obligation builder, Kafka, and bank workers
- Reconcile and closeBank settlement evidence and
Freeze inputs, calculate and approve one version, then create and reconcile each authorized payment.
- State ownership
- PostgreSQL owns the approved version and obligations. The bank supplies settlement evidence.
- Scale
- Partition calculation work by employee bucket and cap bank traffic separately.
- Correctness
- Approval binds the reviewed version and total. Each obligation keeps one logical payment ID.
- Failure and recovery
- After a timeout or failover, look up the original payment before authorizing another submission.
Payroll architecture
Trace the calculation lane on the left and payment lane on the right. An exact-version approval in PostgreSQL authorizes the obligations that enter the payment lane.
- Edge
- Compute
- State
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 18 flow steps
Payroll run lifecycle
The approved calculation is frozen. Recalculation creates a new version before approval. Completion depends on settlement and the policy for unresolved exceptions.
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 11 flow steps
Payment claim and timeout recovery
A conditional claim stops concurrent local ownership. When the bank outcome is unclear, checks the original payment identity before any eligible retry.
- Messaging
- State
- Compute
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 10 flow steps
High-level design component walkthrough
Payroll Admin
Schedule, review and approve a run.
Why, tradeoff and connected operations
Human approval authorizes the reviewed calculation.
Tradeoff: Approval can delay a run past the funding cutoff.
Connected operations: Create run; Approve reviewed version
Payroll API and Orchestrator
Authorize tenant requests, manage the run, and effective HR and time inputs.
Why, tradeoff and connected operations
Freeze the calculation inputs before and scope every request to the employer.
Tradeoff: Persist bounded work and progress so restarts can resume.
Connected operations: Create run; Read versioned inputs; Save and
HR and Time Data
Supply eligible employees and effective inputs.
Why, tradeoff and connected operations
The HR system remains the source of master records.
Tradeoff: Incomplete input can block readiness.
Connected operations: Read versioned inputs
PostgreSQL Financial State
Own runs, results, approvals, obligations, attempts, audit and rows.
Why, tradeoff and connected operations
PostgreSQL binds approvals, payment obligations and intent in transactions. Constraints and conditional state changes make financial retries auditable. suits related financial records; a key-value design would need equally careful transaction boundaries.
Tradeoff: Partition by company or financial and limit large transactions.
Connected operations: Save and ; Relay committed events; Save versioned results; Commit approval and ; Save obligations and ; Claim and record attempt; Verify and record outcome
Outbox Relay
Publish committed work with stable identities.
Why, tradeoff and connected operations
The bridges PostgreSQL and Kafka through failures.
Tradeoff: Confirmations can be lost and cause repeat delivery.
Connected operations: Relay committed events; Queue calculations; Dispatch approved run; Queue approved payments
Kafka: Calculation Work
Buffer versioned employee tasks.
Why, tradeoff and connected operations
Partition by run and work bucket and control per-tenant admission.
Tradeoff: Monitor the oldest unprocessed calculation.
Connected operations: Queue calculations; Deliver employee buckets
Calculation Workers
Calculate gross, tax, deductions and net pay.
Why, tradeoff and connected operations
Persist one result per employee and calculation version.
Tradeoff: Bound concurrency at the tax dependency.
Connected operations: Deliver employee buckets; Calculate tax and deductions; Save versioned results
Tax and Deduction Engine
Evaluate versioned tax and deduction inputs.
Why, tradeoff and connected operations
Existing tax logic can be reused with provenance.
Tradeoff: Version and capacity must be available at calculation time.
Connected operations: Calculate tax and deductions
Review and Approval
Check complete totals and commit approval of the exact version.
Why, tradeoff and connected operations
A conditional transition prevents approval of stale review data.
Tradeoff: New versions require a new review.
Connected operations: Approve reviewed version; Commit approval and
Build Obligations
Expand approved items into durable payment obligations.
Why, tradeoff and connected operations
Use a bounded and unique keys for resumable expansion.
Tradeoff: Batching adds propagation delay after approval.
Connected operations: Dispatch approved run; Save obligations and
Kafka: Payment Work
Deliver approved payment IDs to a separate fleet.
Why, tradeoff and connected operations
Keep calculation pressure separate from bank limits.
Tradeoff: Redelivery does not grant worker ownership.
Connected operations: Queue approved payments; Deliver obligations
Payment Workers
Claim one obligation and call the provider with a stable identity.
Why, tradeoff and connected operations
PostgreSQL guards the attempt generation.
Tradeoff: Unknown external outcomes require .
Connected operations: Deliver obligations; Claim and record attempt; Submit stable payment ID
Bank / ACH Provider
Accept transfers and provide status and settlement evidence.
Why, tradeoff and connected operations
Stable request identity enables safe lookup or retry under its contract.
Tradeoff: An acknowledgement does not establish settlement.
Connected operations: Submit stable payment ID; Send settlement evidence
Reconciliation
Match webhooks, status lookups and settlement files.
Why, tradeoff and connected operations
Close original obligations based on verified evidence.
Tradeoff: Unmatched evidence can require manual review.
Connected operations: Send settlement evidence; Verify and record outcome
CREATED
A durable run exists for the schedule and period.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Capture effective inputs
SNAPSHOTTING
Collect immutable or versioned calculation inputs.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Capture effective inputs; Dispatch versioned tasks; Freeze new version
CALCULATING
Compute employee items and check expected coverage.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Dispatch versioned tasks; Verify coverage and totals
READY FOR APPROVAL
The calculation version and totals are ready to review.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Verify coverage and totals; Approve reviewed version; Revise before approval; Cancel before approval
RECALCULATE
Start a new version and retain prior results.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Revise before approval; Freeze new version
CANCELLED
Stop eligible work before payment authorization.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Cancel before approval
APPROVED
The exact reviewed calculation is authorized.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Approve reviewed version; Expand approved obligations
PAYMENT PROCESSING
Build obligations and submit eligible transfers.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Expand approved obligations; Verify bank outcomes
RECONCILING
Resolve submitted, unknown and unsettled outcomes.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Verify bank outcomes; Settlement criteria met; Record permitted exceptions
COMPLETED
All obligations satisfy the settlement criteria.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Settlement criteria met
COMPLETED WITH EXCEPTIONS
Document remaining exceptions under the completion policy.
Why, tradeoff and connected operations
PostgreSQL owns the state and enforces allowed transitions.
Tradeoff: Keep transition evidence and retry identity for audit.
Connected operations: Record permitted exceptions
Payment Work Message
Deliver a stable logical payment ID.
Why, tradeoff and connected operations
At-least-once delivery survives worker loss.
Tradeoff: Redelivery can repeat.
Connected operations: Check current state
PostgreSQL Conditional Claim
Move an eligible payment from PENDING to PROCESSING and increment its attempt generation.
Why, tradeoff and connected operations
The same PostgreSQL financial database conditionally claims one eligible payment. The attempt generation prevents a stale worker from overwriting a newer result. This is a transaction in the existing store, not an additional database or proof that the bank did nothing.
Tradeoff: A database claim cannot prove what happened at the bank.
Connected operations: Check current state; One row updated; Zero rows updated; Reopen verified safe retry
No Eligible Claim
Acknowledge a stale, terminal, or safely recoverable duplicate.
Why, tradeoff and connected operations
Only the claim winner can proceed.
Tradeoff: Stuck work needs durable recovery.
Connected operations: Zero rows updated
Claimed Payment Worker
Keep the same logical payment ID throughout its attempts.
Why, tradeoff and connected operations
The attempt generation fences stale local writes.
Tradeoff: Unknown effects may require provider evidence.
Connected operations: One row updated; Submit same payment ID
Bank / ACH Provider
Accept or look up a transfer using its original identity.
Why, tradeoff and connected operations
Provider protects repeated calls within its contract.
Tradeoff: A timeout does not establish failure.
Connected operations: Submit same payment ID; Confirmed outcome; Timeout or uncertain result
Accepted or Settled
Record the verified provider outcome and distinguish acceptance from settlement.
Why, tradeoff and connected operations
The run only completes after its settlement criteria are met.
Tradeoff: Confirmation can be delayed.
Connected operations: Confirmed outcome; Verified accepted or settled
UNKNOWN Outcome
Keep an unclear submission durable and block blind retries.
Why, tradeoff and connected operations
A provider may have acted before the response was lost.
Tradeoff: Uncertain obligations may stay pending.
Connected operations: Timeout or uncertain result; Look up original transfer
Reconcile Original Payment
Check webhook, status lookup or settlement file.
Why, tradeoff and connected operations
resolves ambiguity with provider evidence.
Tradeoff: Missing evidence requires review.
Connected operations: Look up original transfer; Verified accepted or settled; Reopen verified safe retry; Still unresolved
Hold for Investigation
Keep unresolved payments out of automatic retry.
Why, tradeoff and connected operations
Protect against duplicate transfers without evidence.
Tradeoff: Manual handling may delay payroll.
Connected operations: Still unresolved
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Additional technical detail
Scope and existing systems
US payroll, including different state tax jurisdictions. HR owns employee master data. The existing tax engine owns tax rules. Payroll owns runs, approvals, payment instructions, settlement tracking, and audit.
Processing lifecycle
- Create run. Scheduler or administrator creates an idempotent payroll run; database commit also writes dispatch intent to the .
- inputs. Capture eligible employee IDs, effective compensation, jurisdiction, time data and relevant benefit/tax-rule versions.
- Calculate. Fan out employee-level tasks from the durable queue; call existing tax engine; persist itemized gross/tax/deduction/net results, uniquely keyed to version.
- Finalize for review. Validate expected item coverage, errors, payroll totals, funding/cutoff requirements, and freeze an immutable calculation version.
- Approve. Employer approves the exact version/hash and totals; persist approval with a conditional transition.
- Build obligations. Expand approved items into uniquely keyed payment obligations through bounded, resumable work; transactional ensures durable dispatch.
- Submit payments. Workers acquire database ownership and send a stable identity to the bank; record submission status and provider reference.
- Reconcile. Match callbacks, inquiries and bank settlement files; resolve UNKNOWN statuses without blindly resubmitting payments.
- Complete and audit. Mark run complete or completed-with-exceptions only after defined settlement/ criteria are satisfied.
API examples
Create a payroll run with a request key. The status in the response is illustrative because calculation progresses asynchronously.
POST /v1/companies/C123/payroll-runs
Idempotency-Key: create-C123-2026-11-01
{ "payPeriodStart":"2026-11-01", "payPeriodEnd":"2026-11-15",
"paymentDate":"2026-11-20", "payScheduleId":"SCHEDULE-01" }
202 Accepted
{ "runId":"RUN-789", "status":"CALCULATING", "employeeCount":100000 }Approve the version, total and hash that the administrator reviewed.
POST /v1/payroll-runs/RUN-789/approve
Idempotency-Key: approve-RUN-789-v3
{ "calculationVersion":3, "expectedRecordVersion":8,
"expectedTotalNetPayMinor":25000000000, "snapshotHash":"sha256:..." }Financial transactions
The approval transaction verifies tenant authorization and the reviewed hash and totals before inserting the approval and row. It rolls back unless the conditional update matches one row.
BEGIN;
UPDATE payroll_runs
SET status='APPROVED', version=version+1
WHERE run_id=:run_id AND status='READY_FOR_APPROVAL'
AND calculation_version=:expected_calculation_version
AND version=:expected_record_version
RETURNING run_id;
-- Require exactly one row; verify snapshot hash/totals and authorization.
INSERT INTO approvals (...) VALUES (...);
INSERT INTO outbox_events (...) VALUES (...);
COMMIT;The payment worker calls the bank only after the claim commits. An expired on a potentially submitted transfer goes to .
UPDATE payments
SET status='PROCESSING', worker_id=:worker,
lease_until=:lease_until, generation=generation+1
WHERE payment_id=:payment_id AND status='PENDING'
RETURNING generation;
-- 1 row = winner; 0 rows = do not submit.Observability and operational readiness
| Area | Signals and alerts |
|---|---|
| Payroll run | time-to-calculate, stuck CALCULATING / APPROVAL state, missing eligible items, totals mismatches |
| Queue health | oldest-event age, backlog, delivery duplicates, poison tasks |
| Fairness | per-tenant queue wait time, throughput, quota rejects, completion by tenant size |
| Payment pipeline | unknown-outcome age, duplicate-claim conflicts, expiries, provider timeouts |
| Bank | unmatched settlements, callback delay, accepted-but-not-settled age |
| Multi-region | replication lag, changes, failover duration, old-owner rejected writes |
| Security | cross-tenant access attempts, audit gaps, unauthorized approval attempts |
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Approve exactly what was reviewed | Immutable versions take storage and require explicit corrections. |
| Recover a payment after a timeout | A safe retry depends on the provider contract. Unresolved payments can wait for evidence. |
| Scale calculations without starving small employers | Fair scheduling adds coordination and can delay work when capacity is tight. |
| Recover work after a committed approval | At-least-once delivery requires stable work keys and idempotent consumers. |
| Resume safely after regional failure | Synchronous cross-region durability costs latency. Asynchronous copies can lose recent acknowledged writes. |
Production scars & failure modes
The bank may have accepted a payroll transfer, but the payment worker lost the response.
Look for: Trace the approved obligation, attempt generation, provider identity and settlement evidence.
Recovery and invariant: Hold the obligation in UNKNOWN and reconcile the original submission before permitting a retry.
| Component / failure | Required behavior / recovery | Operational implication |
|---|---|---|
| Approval commits during a Kafka outage | Replay the durable event. Deduplicate obligation creation. | Track the oldest unpublished event. |
| Bank call times out or worker loses its | Keep the outcome unknown and reconcile the original payment ID. | A replacement worker needs evidence or a provider-backed safe retry. |
| A region loses financial authority | Fence the old writer and reconcile in-flight payments before resuming. | Name the replication loss window. Pause transfers while state is uncertain. |
90-second interview summary
I would create a payroll run in PostgreSQL and freeze effective HR, time and tax inputs. Kafka spreads calculations across employee buckets, with tenant limits to protect smaller runs. The employer approves the exact calculation version and total.
Approval and the commit together. Resumable batches create unique payment obligations for a separate worker fleet. Each worker claims one obligation in PostgreSQL and submits a stable payment ID to the bank. If the call times out, I reconcile that ID before retrying. Provider acceptance and settlement are separate states.
I would keep one fenced writer per financial and pause uncertain transfers during failover. The design gives up some availability when payment state is unclear, which is preferable to paying the same obligation twice.
Practice questions and answers
Illustrative exercises. Predict the outcome before revealing the explanation.
The employer reviewed version 3, but version 4 completed before approval. What should happen?
Reject the stale approval. Require the employer to review and approve the current immutable version and matching total and hash.
A payment lease expires after a bank timeout. Can the next worker submit another payment?
An expired cannot prove the bank did nothing. Reconcile the original payment identity first, then follow the provider contract for a safe retry.
Approval committed, but the publisher could not reach Kafka. What work was lost?
The approval event remains in the PostgreSQL . Republish the same event ID and resume obligation expansion with durable work keys.
Explain it without looking
Explain approve exactly what was reviewed
Reveal answer
Approve the frozen calculation version, total and hash in PostgreSQL.
Compensation can change while a run is under review.
Immutable versions take storage and require explicit corrections.
Explain recover a payment after a timeout
Reveal answer
Claim one obligation, submit its stable payment ID, and reconcile an unknown result before retrying.
A timeout can hide a transfer the bank already accepted.
A safe retry depends on the provider contract. Unresolved payments can wait for evidence.
Explain scale calculations without starving small employers
Reveal answer
Split runs into employee buckets, cap each tenant’s concurrency, and budget calculation and payment workers separately.
A large tenant can saturate the tax dependency or crowd out smaller runs.
Fair scheduling adds coordination and can delay work when capacity is tight.
Explain recover work after a committed approval
Reveal answer
Commit approval and together, then create obligations in resumable batches.
A crash can happen before or after the relay publishes.
At-least-once delivery requires stable work keys and idempotent consumers.
Explain resume safely after regional failure
Reveal answer
Fence the old financial writer and reconcile in-flight payment IDs before replay.
A standby can lack a result for a transfer already applied at the bank.
Synchronous cross-region durability costs latency. Asynchronous copies can lose recent acknowledged writes.
Revision checklist
Revision checklist
- Reconstruct approve exactly what was reviewed: Approve the frozen calculation version, total and hash in PostgreSQL.
- Reconstruct recover a payment after a timeout: Claim one obligation, submit its stable payment ID, and reconcile an unknown result before retrying.
- Reconstruct scale calculations without starving small employers: Split runs into employee buckets, cap each tenant’s concurrency, and budget calculation and payment workers separately.
- Reconstruct recover work after a committed approval: Commit approval and together, then create obligations in resumable batches.
- Reconstruct resume safely after regional failure: Fence the old financial writer and reconcile in-flight payment IDs before replay.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope calculation, approval, payment, and settlement. Use about 700 calculations per second for the four-hour window and size bank submission separately. |
| 15–30 min | High-level design | Trace frozen inputs through calculation and review. Show approval, obligation creation, submission, and . |
| 30–45 min | Deep dives | Explain how an approval binds the reviewed version, total, and hash. Walk through a lost bank response using the original payment ID. |
| 45–55 min | Failure and recovery | Walk through an replay or regional failure. Fence the old writer and resolve in-flight payments before replaying. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Practice questions and answers
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough