Distributed Event Ledger, Pay Engine, Workflow Orchestration, and AI Query Assistant
System DesignModel answerLast updated
Design four backend systems: a deduplicated event counter, an immutable driver-pay ledger, a fault-tolerant offboarding workflow, and a permission-gated LLM expense assistant.
Background
Your platform serves a workforce-management product. Mobile and web clients emit usage events, field workers earn pay that must be settled exactly, employees leave and their access must be fully revoked, and managers want natural-language answers over expense records. You need to design four cooperating subsystems in a single interview session.
Constraints
- Mobile SDKs may reconnect after hours offline and flush large backlogs. Events may arrive out of order, duplicated, or late — none can be silently dropped.
- Real-time dashboards can tolerate stale data up to tens of minutes; monthly billing figures must be exact and auditable.
- Offboarding touches seven to ten external services. Some steps can run in parallel, some have hard prerequisites, and some cannot be safely retried without a compensating action.
- The expense assistant operates over two large datasets that span multiple tenants. Data boundaries must be enforced before any model call.
What to clarify before designing
- For the event system: which fields uniquely identify a billing event, and which fields are mutable labels added after the fact?
- For driver pay: when a rate is renegotiated, does it apply only to work completed from that point forward, or can it reopen unsettled past periods?
- For offboarding: which external systems expose idempotency keys, support outbound webhooks, or offer a compensating "re-grant" action if a later step fails?
Part 1 — Counted and billed events
Design the full pipeline from SDK emission to dashboard widgets and to a monthly billing close.
Cover:
- How events are accepted durably and deduplicated across retries and backlog flushes
- How you handle event-time windowing when events arrive minutes or hours after the clock window they belong to
- Why the approximate dashboard store and the exact billing ledger are separate systems, and how the billing ledger is reconciled at month-end
Part 2 — Field worker pay engine
Model the data layer that tracks completed work, applies effective-dated rate schedules, handles overlapping or duplicate job records, and exposes the difference between what has accrued and what has been paid out.
Cover:
- How work records are kept immutable, and how rate changes are represented without mutating history
- How the system detects and resolves time-span overlaps or duplicate job submissions
- The shape of accrual, payment, and reconciliation APIs
Part 3 — Employee offboarding orchestrator
Design the service that drives a seven-to-ten step deprovisioning process: revoking credentials, closing active sessions, issuing a final pay run, archiving records, and notifying downstream systems.
Cover:
- How the workflow state is persisted so that a crash mid-run can resume from exactly the right step
- Per-step idempotency strategy and what compensation looks like when a late-stage step fails after an earlier one succeeded
- How you minimize wall-clock completion time (parallelism), what triggers retry versus operator escalation, and how inbound webhooks from external systems are wired into the state machine
Part 4 — Natural-language expense assistant
A manager types a free-form question like "Show me all software subscriptions over $500 this quarter for the engineering team." Design the system that safely converts this into structured operations over employee records and expense records, returns correct aggregates, and streams the result back to the UI.
Cover:
- How tenant scope and per-employee data permissions are enforced before the query reaches the model
- How the model's output is turned into a typed, validated query plan rather than executed as raw text
- When you use a deterministic tool call versus a multi-step agent loop
- How streaming is handled without surfacing unvalidated partial results to the user
Hints
Hint 1
For Part 1, think about why you need two separate stores — one optimized for fast approximate reads and one for exact, auditable counts. An append-only ledger with a batch reconciliation job at billing close is a common pattern; ask yourself what the source of truth is when they diverge.
Hint 2
For Part 3, model the workflow as a DAG of steps with explicit states (pending, running, succeeded, failed, compensating). A durable execution engine (or a simple state table with a worker polling it) lets you resume after a crash without re-running completed steps. Draw the critical path first to find which steps block others.
Hint 3
For Part 4, the biggest trap is letting the LLM emit free-form code or queries that execute directly. Instead, constrain its output to a small vocabulary of typed operations (filter, group_by, sum, top_k) that your backend validates before running. Authorization happens on the resolved query plan, not on the raw natural-language string.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to approach this problem
Start by stating the cross-cutting concerns that apply to all four parts: durability over correctness over performance, explicit idempotency at every external boundary, and data authorization enforced at the system layer rather than trusted from the caller. Interviewers at this level want to see that you have a mental checklist for partial failures before you start drawing boxes.
Part 1 — Event counter and billing ledger
Ingestion and deduplication. Clients attach a client-generated event ID (UUID or deterministic hash of session + sequence number). The ingestion tier writes to a durable queue (Kafka or a cloud equivalent) and returns 202 immediately. A downstream consumer performs exactly-once writes into an event store keyed on event ID — duplicates are dropped by a unique constraint or a Redis Bloom filter with a fallback exact check. Late events from an offline backlog land in the same queue; the consumer uses the event's own timestamp, not arrival time, for windowing.
Dashboard vs. billing separation. Dashboards are served from a pre-aggregated OLAP store (Druid, ClickHouse, or BigQuery materialized views) that is refreshed every few minutes. Approximate is fine here — you trade strict accuracy for query speed. Billing is a separate append-only ledger table: one row per deduplicated event with its billing dimensions and a status column (pending → closed). At month-end a reconciliation job scans pending rows, validates them against the raw event store, and flips them to closed in a single transaction. If the aggregate diverges from the dashboard number by more than a configurable threshold, it pages an on-call operator rather than silently accepting the discrepancy.
Late-data policy. Accept events up to N days late (e.g., 7 days for mobile offline scenarios). After the cutoff, events are quarantined and require manual review before they can enter billing. Dashboard windows ignore quarantined events; the billing ledger does not close a period until the quarantine window has elapsed.
Part 2 — Driver pay engine
Immutable work records. Each completed job is an immutable row: driver ID, job ID, start time, end time, gross duration, and a snapshot of the rate in effect at job-end. You never update this row. If a job is disputed and corrected, you insert a reversal row (negative amount) and a replacement row — the ledger always reflects history.
Effective-dated rates. A rate_schedule table has rows of (driver_id, rate_cents_per_hour, effective_from, effective_to). When a job is settled, the settlement job joins against the rate row whose window contains the job's end timestamp. A rate change never reaches backward into already-settled rows; it only applies to jobs settled after the new effective date. Unsettled historical jobs are a policy decision you surface to the interviewer — document that assumption clearly.
Overlap and duplicate detection. Before inserting a new job record, query for any existing jobs for the same driver where the time spans intersect (start < existing.end AND end > existing.start). Surface overlaps to an admin queue rather than auto-resolving, because the resolution strategy (keep longest, keep both, merge) is domain-specific.
Reconciliation API. Expose three aggregations: accrued(driver_id, period) — sum of all settled job amounts; paid(driver_id, period) — sum of all payment transactions; outstanding = accrued − paid. Payment transactions are also immutable rows; no negative balances allowed without an explicit credit record.
Part 3 — Offboarding orchestrator
State machine persistence. Store each workflow instance as a row in an offboarding_runs table with a JSON blob of step states. Each step has its own status: pending, in_progress, succeeded, failed, compensating, compensated. A pool of workers polls for runnable steps (prerequisites all succeeded, step is pending). On pickup, the worker atomically sets status to in_progress with a heartbeat timestamp. A supervisor process reclaims rows whose heartbeat has expired — this handles worker crashes.
DAG and critical path. Map your seven to ten steps into a dependency graph. Example: revoke SSO → revoke VPN and revoke email (parallel) → archive mailbox (depends on revoke email) → final pay run (no dependencies) → notify HR (depends on pay run). Run everything on the critical path first and saturate the parallel branches. This minimizes wall-clock time, which matters for security-sensitive steps like credential revocation.
Idempotency and compensation. Every step call includes the workflow ID and step ID as an idempotency key. External systems that support idempotency keys use them directly. For systems that do not, the worker checks step status before calling — if the step already shows succeeded in the state table, skip the call. Compensation means you have a defined rollback action for each step (e.g., if archiving fails after SSO was revoked, you cannot un-revoke SSO, so the compensating action is to page a human with the exact state rather than attempt automated undo). Not every step has an automated compensating action — that is the honest answer.
Escalation. After three retries with exponential backoff, a failed step transitions to needs_operator. The workflow pauses (it does not roll back everything). An operator can manually mark a step succeeded (if they fixed it externally) or failed (triggering compensation from that point). Webhooks from external systems can push step completion events into a /webhooks/{workflow_id}/{step_id} endpoint that advances the state machine without polling.
Part 4 — Expense assistant
Authorization first. When a query arrives, resolve the caller's tenant ID and their data-access role (manager scope vs. self-only). Attach these as a permission context object. This object is passed to every downstream operation — the model never receives raw data it is not allowed to see, and the query planner filters datasets to the permitted employee IDs before any rows are fetched.
Typed query plan, not raw code. The LLM receives the natural-language question, a schema summary, and a small set of allowed operation types: filter(field, op, value), group_by(field), aggregate(func, field), top_k(n, field), date_range(start, end). It returns a JSON query plan. Your backend validates the plan against a JSON Schema, checks that every referenced field exists and is permitted for this tenant, then executes it deterministically. The model never emits SQL or Python that runs directly.
Agent vs. single-shot tool call. Use a single-shot tool call when the question maps cleanly to one query plan — most expense lookups fall here. Use a multi-step agent loop only when the question requires chaining results (e.g., "find the team with the highest spend, then list their top five vendors") — each step's output is validated before feeding it into the next prompt. Keep agent loops shallow (two to three steps max) to limit error accumulation.
Streaming without leaking. Buffer the full query result server-side, validate the aggregate totals for sanity (e.g., a sum cannot exceed a known maximum), then open a streaming response to the client. Never stream raw model output directly — stream only the validated, structured result. If validation fails, return a non-streaming error explaining why the answer could not be produced safely.
Common mistakes to call out. Letting the LLM output freeform queries; enforcing authorization in the prompt rather than in code; streaming partial results before the permission check completes; treating all steps of the offboarding DAG as retryable without checking which ones are idempotent.