Employee Onboarding Workflow
The laptop provider accepts an order, then the worker crashes before saving success.
Topic tools
Layout updated
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 / input | Response and retry contract |
|---|---|
POST/v1/onboardings | 202 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}/versions | 201 for a validated immutable definition; no implicit migration of active runs. |
POST/v1/onboardings/{runId}/migrations | 202 for an explicit audited migration to a definition version; report running-effect exceptions. |
POST/v1/onboardings/{runId}/approvals | 200 after validating approver permission and current workflow generation. |
High-level design
How to draw this design
- Configure and startHR admin, gateway, workflow configuration, and onboarding service
- Schedule ready stepsOrchestrator, PostgreSQL workflow state, and publisher
- Execute integrationsKafka, execution workers, adapters, and providers
- 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.
- 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 20 flow steps
High-level design component walkthrough
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 · 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
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
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
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
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 +
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
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
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
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
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
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 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
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.
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.
- 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
202with a run ID after commit. - 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.
- 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.
- 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.
- 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.
| Path | Sequence | Authority and failure behavior |
|---|---|---|
| Configure before starting a run | HR → gateway → Workflow Configuration Service → PostgreSQL | Validate dependencies, reject cycles, and publish an immutable version. Existing runs keep their version until an explicit migration. |
| Track an existing run | HR → 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 operation | Callback Receiver / Reconciler → provider lookup → PostgreSQL → next orchestration scan | Persist 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
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Persist the workflow before acknowledging | Database 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 effects | A cannot stop an old worker at an external provider. Unknown outcomes require ; unsupported providers may require manual resolution. |
| Change active workflows deliberately | Pause pending dispatch, invalidate queued work by generation, and reconcile running effects. Completed actions may need compensation or manual handling. |
| Bound provider load and isolate tenants | Fairness and safety delay large imports; completion targets must account for third-party outages. |
| Recover across regions without repeating effects | Synchronous replication adds latency and can reduce write availability during partitions; asynchronous replication has nonzero . |
Production scars & failure modes
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 / failure | Required behavior / recovery | Operational implication |
|---|---|---|
| Worker dies after claiming | Expire and recover using the same operation key; fence stale database updates | Step remains running. External providers need their own or contract. |
| Provider accepts but response is lost | Query by operation identity or retry with the same supported key; otherwise pause for review | External outcome is unknown. Blind retries can duplicate laptop orders or enrollment. |
| Database commit succeeds; publisher crashes | Relay retries the committed event | Task has not reached Kafka. At-least-once publication requires duplicate-safe consumers. |
| Provider outage or tenant bulk import | Isolate provider concurrency, apply tenant quotas and retry with bounded backoff | Backlog and delayed onboarding. Show blocked status; do not claim a fixed completion SLA during outages. |
| Redis unavailable | Bound database fallback and use explicit stale/unavailable responses when overloaded | Progress 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
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope onboarding steps, dependencies, and approval. Estimate concurrent workflows and identify provider limits. |
| 15–30 min | High-level design | Trace a versioned workflow run through PostgreSQL, the orchestrator, , Kafka, workers, and provider callbacks. |
| 30–45 min | Deep dives | Explain step scheduling and stable operation keys. Show how verified outcomes release dependent steps. |
| 45–55 min | Failure and recovery | Walk through a provider timeout or expired worker . Reconcile the original operation before replaying it. |
| 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