System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Employee Onboarding Workflow

The laptop provider accepts an order, then the worker crashes before saving success.

● HardSystem 202 min2 prerequisites
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

Problem statement

Design a configurable onboarding workflow for new hires. Coordinate tasks across HR, IT, and finance, and start dependent tasks only after their prerequisites succeed.

Functional requirements

  • Accept employee onboarding and return a durable run identifier.
  • Configure versioned company workflows with dependencies and approval gates.
  • Execute account, payroll, document and device integrations.
  • Expose per-step progress, blocked reasons, retry state and audit history.
  • Recover interrupted work and explicitly migrate or cancel active runs.

Non-functional requirements

  • Accepted requests survive the declared storage failure domain.
  • Progress can lag; execution and approval gates use authoritative state.
  • Tenant authorization, bounded bulk admission and provider isolation are required.
  • Make retry and external-effect guarantees explicit; no universal exactly-once claim.

Back-of-the-envelope estimates

Illustrative estimate
50,000 customer companies; 100,000 onboardings/day
100,000 / 86,400 = about 1.16 starts/second; brief 10x peak is about 12/second
At 10 steps/run: about 1 million initial step executions/day

Entities

Entity / logical owner
WorkflowDefinition (tenant, workflow, version)
OnboardingRun (tenant, run)
StepExecution (tenant, run, step)
OutboxEvent (same PostgreSQL database)
Attempt / approval / audit records

API design

Operation / inputResponse and retry contract
POST/v1/onboardings202 after durable commit; tenant-scoped key returns the existing run for a matching retry.
GET/v1/onboardings/{runId}200 with per-step status and blocked reasons; enforce tenant authorization.
POST/v1/workflows/{id}/versions201 for a validated immutable definition; no implicit migration of active runs.
POST/v1/onboardings/{runId}/migrations202 for an explicit audited migration to a definition version; report running-effect exceptions.
POST/v1/onboardings/{runId}/approvals200 after validating approver permission and current workflow generation.

High-level design

How to draw this design

  1. Configure and startHR admin, gateway, workflow configuration, and onboarding service
  2. Schedule ready stepsOrchestrator, PostgreSQL workflow state, and publisher
  3. Execute integrationsKafka, execution workers, adapters, and providers
  4. Recover and trackCallbacks, reconciler, tracking service, and optional Redis cache

Create a run from an immutable definition. Schedule ready steps, execute them, and unlock dependents after verified results.

State ownership
PostgreSQL owns step state, leases, operation identities, and dispatch intent.
Scale
Set separate concurrency budgets for each provider and work type.
Correctness
Commit the scheduled step and together. Retries reuse the saved operation identity.
Failure and recovery
Reconcile a timeout or expired worker before repeating an external effect.
Employee Onboarding — Durable Workflow and External Effects
G hr->api 1. Send HR request api->onboarding 2. Start onboarding onboarding->db 3. Commit run db->orch 4. Scan eligible steps orch->db 5. Schedule + outbox db->relay 6. Poll outbox relay->queue 7. Publish to Kafka queue->workers 8. Deliver task workers->db 9. Claim + save key workers->adapters 10. Execute claimed step adapters->providers 11. Call with stable key providers->results 12. Signed callback workers->results 13. Sync result results->providers 14. Reconcile results->db 15. Store outcome api->config 16. Configure workflow config->db 17. Publish version api->status 18. Read run progress status->cache 19. Read cached progress status->db 20. Read on miss hr HR Admin / Company edge api Gateway · LB / Auth / Rate limits edge config Workflow Configuration Service compute onboarding Onboarding Service compute status Tracking Service compute orch Workflow Orchestrator compute db PostgreSQL: Workflow State and Outbox state · durable cache Redis Progress Cache · Optional state · memory relay Outbox Publisher compute queue → Kafka / Task Queues messaging workers Execution Workers compute results Callback Receiver / Reconciler compute providers External Providers compute adapters Integration Adapters compute
  • Edge
  • Compute
  • State
  • Messaging

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.

Read the 20 flow steps

High-level design component walkthrough

Client / user

HR Admin / Company

Configure workflows, start runs and read progress.

Why, tradeoff and connected operations

Keep human approvals and operational exceptions visible.

Tradeoff: Progress is eventually refreshed; approval authorization is checked server-side.

Connected operations: Send HR request

Gateway / routing

Gateway · LB / Auth / Rate limits

Balance traffic, authenticate HR and rate-limit by tenant and route.

Why, tradeoff and connected operations

Route run creation, workflow configuration and status queries to their own handlers.

Tradeoff: Each handler still enforces tenant authorization for the requested resource.

Connected operations: Send HR request; Start onboarding; Configure workflow; Read run progress

Backend service

Workflow Configuration Service

Validate the dependency graph and publish immutable workflow versions.

Why, tradeoff and connected operations

A run refers to a specific definition, so an edit does not silently change its gates.

Tradeoff: Moving an active run to a new version requires an explicit migration.

Connected operations: Configure workflow; Store immutable version

Backend service

Onboarding Service

Validate the employee, workflow version and request identity. Commit the run and initial steps.

Why, tradeoff and connected operations

Return a run ID after durable acceptance. Reuse that ID if the client retries.

Tradeoff: The response confirms acceptance. Integration work completes asynchronously.

Connected operations: Start onboarding; Commit run and steps

Backend service

Tracking Service

Authorize tenant-scoped progress reads and return completed, pending and blocked steps.

Why, tradeoff and connected operations

Separate dashboard reads from execution decisions.

Tradeoff: Cache misses must not cause unbounded database load.

Connected operations: Read run progress; Read cached progress; Read through on miss

Coordination / ownership

Workflow Orchestrator

Evaluate dependencies and schedule eligible steps.

Why, tradeoff and connected operations

Multiple instances coordinate through conditional database transitions.

Tradeoff: Polling adds delay; scan all eligible work with indexes and bounded batches.

Connected operations: Read eligible steps; Schedule step +

Relational database

PostgreSQL: Workflow State and Outbox

Own workflow definitions, run and step state, leases, operation keys and the transactional .

Why, tradeoff and connected operations

PostgreSQL commits workflow progress and the next step’s intent together. Conditional claims and unique operation keys keep retries consistent. fits related workflow transitions; the task queue delivers work but does not own completion.

Tradeoff: and workflow tables share one database, not a distributed transaction.

Connected operations: Commit run and steps; Read eligible steps; Schedule step + ; Read committed rows; Claim and save operation key; Commit verified outcome; Store immutable version; Read through on miss

Cache / in-memory index

Redis Progress Cache · Optional

Cache derived progress for active runs.

Why, tradeoff and connected operations

An optional Redis cache serves frequently requested workflow progress. It reduces repeated status reads when traffic warrants it. Redis may be stale or empty; PostgreSQL alone decides step eligibility and completion.

Tradeoff: Stale or lost entries do not determine step eligibility.

Connected operations: Read cached progress

Backend service

Outbox Publisher

Publish committed dispatch events and track acknowledgement.

Why, tradeoff and connected operations

Recover the database-to-broker publication gap.

Tradeoff: A crash after publish can cause redelivery.

Connected operations: Read committed rows; Publish to Kafka

Queue / event stream

Kafka / Task Queues

Buffer tasks for independently limited integration workers.

Why, tradeoff and connected operations

Decouple scheduling from provider throughput.

Tradeoff: Transport is at least once; task state remains authoritative in PostgreSQL.

Connected operations: Publish to Kafka; Deliver task

Backend service

Execution Workers

Claim steps with leases, invoke adapters and persist outcomes.

Why, tradeoff and connected operations

Recover crashed execution while rejecting stale state updates.

Tradeoff: expiry cannot revoke a request at a third party.

Connected operations: Deliver task; Claim and save operation key; Execute claimed step; Submit synchronous result

Backend service

Callback Receiver / Reconciler

Verify callbacks and reconcile uncertain provider outcomes.

Why, tradeoff and connected operations

Make missing responses recoverable without blind new effects.

Tradeoff: Deduplicate callbacks and reject stale state regressions; some outcomes need manual review.

Connected operations: Send signed callback; Submit synchronous result; Look up uncertain outcome; Commit verified outcome

External dependency

External Providers

Perform the requested business operation.

Why, tradeoff and connected operations

Use supported or operation lookup.

Tradeoff: Timeout can mean success; cancellation and differ by provider.

Connected operations: Call with stable key; Send signed callback; Look up uncertain outcome

Backend service

Integration Adapters

Accounts, payroll, documents and devices; stable operation identity.

Why, tradeoff and connected operations

Isolate provider-specific request, retry and status contracts.

Tradeoff: Provider capabilities limit duplicate-effect guarantees.

Connected operations: Execute claimed step; Call with stable key

Deep dives — decisions, failures and recovery

Open a deep dive to follow the steps, try an example and see how recovery works.

Deep dive 1

Persist the workflow before acknowledging

PostgreSQL owns immutable definitions, onboarding runs, step state and dispatch intent.

Read the explanation and worked example
How it works

In one transaction create a run tied to a definition version, its step records and tenant-scoped request identity. Validate the dependency graph before activation. A repeated request with different content under the same identity is rejected.

Walk through an example

A response is lost after the onboarding run commits. The client retries and receives the existing run rather than starting another laptop-order step.

Failure and recovery

A database outage prevents new acceptance. A successful regional commit does not imply zero-loss cross-region failover when replication is asynchronous.

Why this helps

A queue message alone does not capture dependency state or the accepted business request.

What you give up

Database availability bounds admission. Use tenant-scoped request identities so a lost response can be retried safely.

Deep dive 2

Schedule dependencies with an outbox

Evaluate eligible steps and commit scheduled state plus an event in one transaction.

Read the explanation and worked example
How it works

Multiple orchestrators may scan indexed eligible work. A conditional state transition selects the scheduling winner; that transaction also inserts the record. The relay marks publication only after broker acknowledgement. Consumers verify current step state and generation.

Walk through an example

The transaction commits, but the relay crashes after publishing and before recording delivery. It republishes; the second task does not create a second logical execution.

Failure and recovery

Retry unpublished rows. Periodically scan eligible states, not just new employees after a timestamp. Monitor oldest-ready-step and oldest--event age.

Why this helps

A crash between a database update and a separate Kafka publish otherwise leaves ambiguous dispatch.

What you give up

The relay can publish twice. Workers still deduplicate; polling adds bounded scheduling delay and indexed database work.

Deep dive 3

Recover claims without repeating external effects

Use conditional claims with leases and persist one operation key per logical step before the provider call.

Read the explanation and worked example
How it works

A worker claims an eligible step using a conditional update and records a owner and generation. It persists a logical operation key before calling the provider. Heartbeats extend active leases; recovery preserves the same key and rejects stale-owner writes.

Walk through an example

A laptop order succeeds remotely and its response disappears. The replacement worker retries or queries using the persisted step identity. A later authorized replacement laptop uses a new operation identity.

Failure and recovery

A is not external . Providers must honor key for the retry horizon or support lookup. Otherwise mark the result unknown and reconcile or request manual action rather than pretending is guaranteed.

Why this helps

expiry recovers abandoned work, while provider protects against overlapping or repeated calls.

What you give up

A cannot stop an old worker at an external provider. Unknown outcomes require ; unsupported providers may require manual resolution.

Deep dive 4

Change active workflows deliberately

Version definitions and explicitly migrate affected runs when a new approval is mandatory.

Read the explanation and worked example
How it works

Create a new immutable definition, pause affected runs and record a migration generation under the same run-level coordination used for dispatch authorization. Map completed steps, insert new approval gates and invalidate queued old-generation work. Reconcile calls already in flight.

Walk through an example

Manager approval becomes mandatory while an account exists and a laptop task is queued. The account stays recorded, the queued task is blocked under the new generation, and only verified approval releases it.

Failure and recovery

A request already sent cannot be revoked by a local state update. Define cancellation, compensation and manual exceptions for those effects. Keep the run paused where safe migration cannot be established.

Why this helps

Changing a status column cannot retract a provider request that has already left a worker.

What you give up

Pause pending dispatch, invalidate queued work by generation, and reconcile running effects. Completed actions may need compensation or manual handling.

Deep dive 5

Bound provider load and isolate tenants

Use separate provider concurrency limits and fair tenant admission; measure queue age rather than only queue size.

Read the explanation and worked example
How it works

Accept a bulk request durably, expand it in bounded batches, and admit eligible steps under tenant and provider budgets. Retry transient failures with backoff and , cap attempts and deadlines, and expose blocked or manual-review states. Keep execution decisions out of Redis.

Walk through an example

One company submits 10,000 employees while the laptop vendor is unavailable. Device tasks accumulate without exhausting the payroll worker pool or preventing another company from creating accounts.

Failure and recovery

Monitor oldest eligible step, lag, expiry, unknown outcomes and provider error rates. Pause unhealthy integrations and resume gradually. Bound status-cache fallback so Redis failure cannot overload the workflow database.

Why this helps

Low average onboarding volume can hide bursty fan-out and slow external dependencies.

What you give up

Fairness and safety delay large imports; completion targets must account for third-party outages.

Deep dive 6

Recover across regions without repeating effects

Keep one write authority per run and explicitly choose the durability boundary before acknowledging onboarding.

Read the explanation and worked example
How it works

Use high availability within the primary region and a deliberate regional recovery policy. With asynchronous disaster recovery, state and operation identities may lag; stop the old writer, recover trustworthy history, and reconcile uncertain provider effects before resuming execution.

Walk through an example

A laptop order succeeds immediately before a regional outage, but its result is absent from the surviving replica. A new region must recover the original operation identity and query the provider rather than create a fresh order.

Failure and recovery

Fence stale database owners and preserve audit evidence. If the operation identity or provider outcome cannot be recovered, pause that step for manual . Zero-loss acknowledged state across regional failure requires an appropriate synchronous cross-region durability policy.

Why this helps

Writer , state durability and external-effect are separate guarantees.

What you give up

Synchronous replication adds latency and can reduce write availability during partitions; asynchronous replication has nonzero .

Additional technical detail

Follow one employee from request to completion

Assume HR has published workflow version 7. The workflow creates an employee account, waits for manager approval before ordering a laptop, and enrolls the employee in payroll when its own prerequisites are satisfied. The three entry points in the diagram handle starting a run, publishing a definition, and reading progress.

  1. Accept the run. HR sends an employee reference, workflow version and request key. The gateway balances traffic, authenticates the tenant and rate-limits admission. The Onboarding Service validates the request, then commits the run, its initial steps and the request key to PostgreSQL. It returns 202 with a run ID after commit.
  2. Schedule eligible work. The Workflow Orchestrator reads due or newly unblocked steps from PostgreSQL. An indexed scan lets it recover work even if a wake-up is missed. A conditional update changes an eligible step to scheduled and inserts its dispatch event into the transactional in the same commit.
  3. Deliver the task. The Publisher reads committed rows from the table in PostgreSQL, publishes each event to Kafka, and records the broker acknowledgement. A crash after publication may cause redelivery. The step remains the durable execution record.
  4. Execute one step. A worker checks the run generation and approval gates, claims the step with a , and records a stable operation key before calling the adapter. The adapter maps the request to the account, payroll, document or device provider. It reuses the operation key for retries of the same effect.
  5. Record the result and unlock dependants. A verified synchronous result or authenticated callback updates PostgreSQL. looks up an unresolved result by its original provider reference. The next orchestration scan can schedule steps whose dependencies now succeeded. If the manager has yet to approve the laptop, that step remains blocked even after the account exists.
PathSequenceAuthority and failure behavior
Configure before starting a runHR → gateway → Workflow Configuration Service → PostgreSQLValidate dependencies, reject cycles, and publish an immutable version. Existing runs keep their version until an explicit migration.
Track an existing runHR → gateway → Tracking Service → optional Redis. Read PostgreSQL on a cache miss and refresh the cache if useful.Authorize the tenant before lookup. Bound the database fallback and label stale progress. Approvals and eligibility always use PostgreSQL.
Recover an uncertain provider operationCallback Receiver / Reconciler → provider lookup → PostgreSQL → next orchestration scanPersist verified evidence against the original operation. If the provider accepted the laptop order but lost the reply, recover its order ID before retrying. Escalate when the outcome cannot be established.

Walk the crash boundary

The laptop vendor accepts the order, then the worker crashes before saving success. PostgreSQL still has the operation key and the running step. After the expires, another worker claims recovery with a newer claim generation and queries the vendor using the saved identity. If it finds the order, it records success and the vendor order ID. A delayed write from the first worker fails its ownership check. If the provider offers neither reliable lookup nor retry , stop automatic ordering and send the case to review.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Persist the workflow before acknowledgingDatabase availability bounds admission. Use tenant-scoped request identities so a lost response can be retried safely.
Schedule dependencies with an The relay can publish twice. Workers still deduplicate; polling adds bounded scheduling delay and indexed database work.
Recover claims without repeating external effectsA cannot stop an old worker at an external provider. Unknown outcomes require ; unsupported providers may require manual resolution.
Change active workflows deliberatelyPause pending dispatch, invalidate queued work by generation, and reconcile running effects. Completed actions may need compensation or manual handling.
Bound provider load and isolate tenantsFairness and safety delay large imports; completion targets must account for third-party outages.
Recover across regions without repeating effectsSynchronous replication adds latency and can reduce write availability during partitions; asynchronous replication has nonzero .

Production scars & failure modes

Failure investigation

The laptop provider accepts an order, then the worker crashes before saving success.

Look for: Inspect operation identity, provider reference, attempt age, ownership and unknown-outcome backlog.

Recovery and invariant: Recover the same operation identity and reconcile with the provider before creating another effect. Record a manual-review state when the provider cannot establish the result.

Component / failureRequired behavior / recoveryOperational implication
Worker dies after claimingExpire and recover using the same operation key; fence stale database updatesStep remains running. External providers need their own or contract.
Provider accepts but response is lostQuery by operation identity or retry with the same supported key; otherwise pause for reviewExternal outcome is unknown. Blind retries can duplicate laptop orders or enrollment.
Database commit succeeds; publisher crashesRelay retries the committed eventTask has not reached Kafka. At-least-once publication requires duplicate-safe consumers.
Provider outage or tenant bulk importIsolate provider concurrency, apply tenant quotas and retry with bounded backoffBacklog and delayed onboarding. Show blocked status; do not claim a fixed completion SLA during outages.
Redis unavailableBound database fallback and use explicit stale/unavailable responses when overloadedProgress reads miss cache. Redis is optional and never the execution authority.

90-second interview summary

HR reaches the gateway, which authenticates and rate-limits the request. Configuration publishes an immutable workflow version. The Onboarding Service pins that version and commits the run, steps and client key in PostgreSQL before returning the run ID.

The orchestrator reads eligible steps and atomically schedules a step and its event in PostgreSQL. The publisher relays the event to Kafka. A worker checks the current generation, claims the step and saves an operation key before its adapter calls the provider.

Synchronous results and verified callbacks update the same workflow state. queries the original provider operation when the result is uncertain. A successful step can unblock its dependants. Tracking reads PostgreSQL on a cache miss and can use optional Redis for derived progress.

Delivery can repeat, so local claims and provider operation identity solve different problems. Explicit migrations protect new approval gates. After a regional outage, recover the durable operation identities and reconcile unresolved calls before resuming them.

Practice questions and answers

Illustrative exercises. Predict the outcome before revealing the explanation.

Can a lease alone stop a duplicate laptop order?

No. A paused worker may resume after expiry. Protect database writes with ownership checks and external calls with stable provider-supported operation identities or .

Must an orchestrator avoid polling?

No. Indexed, bounded polling of eligible states is valid. Its tradeoff is scheduling delay and scan cost; a timestamp-only scan of new employees misses previously blocked steps.

Explain it without looking

Explain persist the workflow before acknowledging

Reveal answer

PostgreSQL owns immutable definitions, onboarding runs, step state and dispatch intent.

A queue message alone does not capture dependency state or the accepted business request.

Database availability bounds admission. Use tenant-scoped request identities so a lost response can be retried safely.

Explain schedule dependencies with an

Reveal answer

Evaluate eligible steps and commit scheduled state plus an event in one transaction.

A crash between a database update and a separate Kafka publish otherwise leaves ambiguous dispatch.

The relay can publish twice. Workers still deduplicate; polling adds bounded scheduling delay and indexed database work.

Explain recover claims without repeating external effects

Reveal answer

Use conditional claims with leases and persist one operation key per logical step before the provider call.

expiry recovers abandoned work, while provider protects against overlapping or repeated calls.

A cannot stop an old worker at an external provider. Unknown outcomes require ; unsupported providers may require manual resolution.

Explain change active workflows deliberately

Reveal answer

Version definitions and explicitly migrate affected runs when a new approval is mandatory.

Changing a status column cannot retract a provider request that has already left a worker.

Pause pending dispatch, invalidate queued work by generation, and reconcile running effects. Completed actions may need compensation or manual handling.

Explain bound provider load and isolate tenants

Reveal answer

Use separate provider concurrency limits and fair tenant admission; measure queue age rather than only queue size.

Low average onboarding volume can hide bursty fan-out and slow external dependencies.

Fairness and safety delay large imports; completion targets must account for third-party outages.

Explain recover across regions without repeating effects

Reveal answer

Keep one write authority per run and explicitly choose the durability boundary before acknowledging onboarding.

Writer , state durability and external-effect are separate guarantees.

Synchronous replication adds latency and can reduce write availability during partitions; asynchronous replication has nonzero .

Revision checklist

Revision checklist

  • Reconstruct persist the workflow before acknowledging: PostgreSQL owns immutable definitions, onboarding runs, step state and dispatch intent.
  • Reconstruct schedule dependencies with an : Evaluate eligible steps and commit scheduled state plus an event in one transaction.
  • Reconstruct recover claims without repeating external effects: Use conditional claims with leases and persist one operation key per logical step before the provider call.
  • Reconstruct change active workflows deliberately: Version definitions and explicitly migrate affected runs when a new approval is mandatory.
  • Reconstruct bound provider load and isolate tenants: Use separate provider concurrency limits and fair tenant admission; measure queue age rather than only queue size.
  • Reconstruct recover across regions without repeating effects: Keep one write authority per run and explicitly choose the durability boundary before acknowledging onboarding.
  • 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

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleScope onboarding steps, dependencies, and approval. Estimate concurrent workflows and identify provider limits.
15–30 minHigh-level designTrace a versioned workflow run through PostgreSQL, the orchestrator, , Kafka, workers, and provider callbacks.
30–45 minDeep divesExplain step scheduling and stable operation keys. Show how verified outcomes release dependent steps.
45–55 minFailure and recoveryWalk through a provider timeout or expired worker . Reconcile the original operation before replaying it.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.
On this page
  1. Problem statement
  2. Functional requirements
  3. Non-functional requirements
  4. Back-of-the-envelope estimates
  5. Entities
  6. API design
  7. High-level design
  8. High-level design component walkthrough
  9. Deep dives — decisions, failures and recovery
  10. Tradeoffs and alternatives
  11. Production scars & failure modes
  12. 90-second interview summary
  13. Practice questions and answers
  14. Explain it without looking
  15. Revision checklist
  16. 60-minute interview walkthrough

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram