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.

Expense and Spend Management Rules Engine

Two employees request $100 each while their department has only $150 remaining.

● HardSystem 2413 min3 prerequisites
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

Problem statement

Design a spend management service for multiple companies. Each company can set policies and limits for corporate card purchases and decide which employee expenses qualify for reimbursement.

Functional requirements

  • Publish immutable, effective-dated company, department, group and employee policies; return allow, deny, require approval or manual review with rule-level reasons.
  • Apply company guardrails to every employee, combine overlapping scopes deterministically, and enforce employee and department budget limits under concurrent requests.
  • Answer live card authorizations immediately, then handle capture, reversal and refund events. An approval-required card decision declines unless a prior approval already exists.
  • Submit receipts and reimbursement claims, approve an exact claim revision, pay once through a provider and expose pending, rejected, paid and unknown outcomes with audit evidence.

Non-functional requirements

  • Target under 150 ms for the internal card decision path and 99.95% service availability. A timely decline counts as a response; monitor dependency-driven declines separately.
  • An approved reservation must never exceed an applicable hard limit at commit time. Use integer minor currency units; scope hard budgets to one agreed currency, with a pinned FX quote for foreign expenses.
  • Reproduce every decision from policy bundle, engine version, employee context, amount, currency, FX quote and time. Isolate tenant data, cache keys, quotas and service credentials.
  • Durable claims and financial state use synchronous multi-zone replication. Regional failover pauses approvals and transfers until authority and in-flight state are established.

Back-of-the-envelope estimates

Illustrative estimate
Assume 10,000 tenants, 1 million cardholders and 2 million card authorizations/day: about 23/s average, 500/s peak.
100,000 reimbursements/day = about 1.2/s average; allow 50/s at month end. 10,000 tenants × 50 rules = 500,000 active rules.
2.1 million decisions/day × 2 KB ≈ 4.2 GB/day, about 1.5 TB/year raw. 100,000 receipts/day × 200 KB ≈ 20 GB/day.

Entities

Entity / logical ownerMinimal authoritative fields and boundary
Policy bundle/version — policy service(tenant_id, bundle_version), effective interval, scoped rules, explicit exception grants and engine version; active pointer updated atomically. Published versions are immutable.
Evaluation/expense — spend service(tenant_id, expense_id), unique processor/request ID and payload hash, claim revision, frozen policy/context/FX inputs, decision and matched rules.
Budget and reservation — spend authority(tenant_id, scope_id, period, currency), limit, settled and reserved amounts; unique authorization ID and state. Reserve all applicable hard-limit rows in one transaction.
Approval/payment obligation — reimbursement serviceExpense revision, approver and context, reserved amount, stable payment ID, attempt and provider evidence. One obligation per approved revision; invalidated revisions cannot pay.
Receipt//audit — object store and spend Private receipt object reference; state transitions and dispatch commit together. Audit records actor, decision inputs, reserve/release and settlement evidence.

API design

Operation / inputResponse and retry contract
POST/v1/policies/{id}/versions201 immutable candidate bundle with scopes, rules and effectiveAt; validate conflicts and bounded rule complexity.
POST/v1/policies/{id}/publish200 activate validated bundle with expectedActiveVersion; 409 for stale admin edit. Version and activation pointer commit together.
POST/v1/card-authorizations200 allow/decline and reasons after decision + reservation; processor request ID deduplicates. This endpoint evaluates and reserves together.
POST/v1/expenses201 claim revision with amount, currency, occurredAt and receipt references; -Key returns the same claim for the same payload.
POST/v1/expenses/{id}/approve202 exact-revision approval, budget reservation, payment obligation and ; 409 if claim or relevant approval context changed.
GET/v1/expenses/{id}200 policy trace, approval revision, reservation, payment and settlement status; signed processor/provider events use separate authenticated adapter ingress.

High-level design

How to draw this design

  1. Configure policiesAdmin apps, policy , and compiled policy bundles
  2. Decide card authorizationCard processor, eligibility context, and authorization service
  3. Reserve and settleTenant financial , reservations, and settlement workers
  4. Reimburse and reviewExpense , private receipts, and payment provider

Evaluate the purchase under the current policy, reserve the budget atomically, then settle or release it using the processor outcome.

State ownership
Tenant financial owns reservations and spend. Policy versions record which rules informed a decision.
Scale
Keep authorization work bounded and separate it from receipt review and reimbursements.
Correctness
Check spending and reserve funds in the same transaction to prevent parallel overspend.
Failure and recovery
Reconcile repeated or out-of-order processor events by their original identity before changing spend.

Expense and Spend Management Rules Engine — architecture

Follow numbered arrows by branch. Solid lines are synchronous calls, dashed lines asynchronous work, and dotted lines provider actions or recovery. The end-to-end walkthrough below connects the main path.

Expense and Spend Management Rules Engine — architecture
G client->policy 1. Publish / claim / approve policy->db 2. Version / approval commit policy->receipts 3. Receipt upload / read processor->engine 4. Authorize request engine->context 5. Resolve scope version engine->cache 6. Load compiled version cache->db 7. Load version on miss engine->db 8. Decision + all holds engine->processor 9. Allow / decline processor->events 10. Capture / reversal events->db 11. Reconcile financial state db->events 12. Relay payment outbox events->bank 13. Pay / look up original ID client Admin / employee apps edge policy Policy + expense API compute db Tenant financial SQL state · durable processor Card processor compute engine Authorize + reserve compute cache Compiled policy bundles state · memory context Employee context authority compute events Settlement / payment workers compute bank Payment provider compute receipts Private receipts state · durable
  • Edge
  • Compute
  • State

━━ 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 13 flow steps

End-to-end flow

  1. An admin publishes a validated immutable bundle using compare-and-swap on the active version. Compile it before activation. Cached bundles are version-addressed; the final authorization transaction verifies the selected active pointer is still current.

  2. A card processor submits a unique authorization ID. The spend service authenticates the tenant, resolves current employee context and the policy effective at authorization time, then computes a deterministic decision.

  3. For allow, one transaction deduplicates the request, locks the employee and department budget rows in stable order, checks all limits and commits the decision plus reservation. Return allow only after commit. A timeout retries the same ID, not a second reservation.

  4. Signed capture/reversal/refund events enter a durable inbox. Move reserved to settled or release remaining holds atomically and deduplicate each event. Reconcile missing events with processor statements; do not blindly release a hold on a local timer.

  5. For reimbursement, evaluate the policy effective on the evidenced expense date and pin it with the claim revision. Receipt review or manager approval is asynchronous. Approval checks current approver authority and claim revision, reserves the current payable budget and creates a payment obligation with .

  6. Payment workers submit one stable payment ID. A timeout becomes UNKNOWN and triggers provider lookup; verified settlement converts reserved to spent. Release only after definitive failure/cancellation. Approval is not payment, and provider acceptance is not settlement.

High-level design component walkthrough

Client / user

Admin / employee apps

Publish policy or submit and approve a claim.

Why, tradeoff and connected operations

Human review remains asynchronous.

Tradeoff: Approver authority must be rechecked.

Connected operations: Publish / claim / approve

Backend service

Policy + expense API

Validate versions, capture claims and authorize exact-revision approvals.

Why, tradeoff and connected operations

One entry point for the slower control and reimbursement flow.

Tradeoff: Does not replace the live authorization path.

Connected operations: Publish / claim / approve; Version / approval commit; Receipt upload / read

Relational database

Tenant financial SQL

Own policy pointers, decisions, budgets, holds, claims, obligations and .

Why, tradeoff and connected operations

PostgreSQL reserves all applicable hard budgets and records the decision in one tenant transaction. It also ties exact-revision approvals to payment obligations and intent. makes related financial updates clear; separate key-value counters would not by themselves protect a shared budget.

Tradeoff: Hot shared-budget rows serialize.

Connected operations: Version / approval commit; Load version on miss; Decision + all holds; Reconcile financial state; Relay payment

External dependency

Card processor

Request authorizations and deliver capture, reversal and refund evidence.

Why, tradeoff and connected operations

External authority for card lifecycle events.

Tradeoff: Timeouts, duplicates and late presentments occur.

Connected operations: Authorize request; Allow / decline; Capture / reversal

Backend service

Authorize + reserve

Evaluate a pinned bundle and atomically reserve hard limits before allow.

Why, tradeoff and connected operations

Eligibility and money availability must both hold.

Tradeoff: Decline if required authoritative state is unavailable.

Connected operations: Authorize request; Resolve scope version; Load compiled version; Decision + all holds; Allow / decline

Cache / in-memory index

Compiled policy bundles

Cache immutable tenant/version rules.

Why, tradeoff and connected operations

An in-memory cache reuses compiled policy bundles by tenant and immutable version. It reduces parsing and evaluation setup on the live card path. The cache speeds evaluation; still verifies the active policy and owns money reservations.

Tradeoff: Active pointer must still be verified at commit.

Connected operations: Load compiled version; Load version on miss

External dependency

Employee context authority

Supply versioned current employee scopes and employment status.

Why, tradeoff and connected operations

Scope evaluation depends on the correct memberships.

Tradeoff: Missing critical context causes decline or review.

Connected operations: Resolve scope version

Backend service

Settlement / payment workers

Persist signed processor inbox events, reconcile holds and relay payable obligations.

Why, tradeoff and connected operations

Separate slow provider work from authorization latency.

Tradeoff: Unknown effects require .

Connected operations: Capture / reversal; Reconcile financial state; Relay payment ; Pay / look up original ID

External dependency

Payment provider

Submit and look up reimbursement transfers with stable payment IDs.

Why, tradeoff and connected operations

Provider evidence resolves whether money moved.

Tradeoff: Acceptance is not settlement.

Connected operations: Pay / look up original ID

Object / blob storage

Private receipts

Store receipts referenced by a claim revision.

Why, tradeoff and connected operations

Private object storage keeps large receipt files outside financial rows. Signed access links allow controlled retrieval without routing every byte through the database. stores the claim and receipt reference; object storage holds the document bytes.

Tradeoff: Signed access and need controls.

Connected operations: Receipt upload / read

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

Define hierarchy and reproducible versions

Apply non-overridable company guardrails first; combine scoped restrictions with deny winning and all required approvals retained.

Read the explanation and worked example
How it works

Company hard-deny and legal/security guardrails cannot be loosened below. For ordinary caps choose the strictest applicable cap; union required approvals and documentation. Specific employee exceptions may relax only marked overridable rules and retain their granting authority. Publish the full resolved rules as an immutable effective-dated bundle. Store employee memberships, evaluation time, engine version and FX inputs with the decision.

Walk through an example

Company meals cap $100 and a group cap $80 produce $80. An employee’s ordinary $150 rule cannot override either. A signed exception may relax the $80 soft cap only if explicitly permitted; a company hard deny still wins.

Failure and recovery

Reject ambiguous/conflicting publication and do not backdate over completed decisions. Reimbursements use the pinned expense-date bundle; a correction creates a new evaluated revision. At approval recheck current approver authority and mandatory current payment restrictions without silently rewriting the historical trace.

Why this helps

Overlapping groups must not produce an answer that depends on evaluation order.

What you give up

Restrictive defaults can surprise admins; show matched reasons and require explicit authorized exceptions rather than last-rule-wins.

Deep dive 2

Reserve shared budgets atomically

Use a tenant-routed transaction for the decision, and all affected hard-limit rows.

Read the explanation and worked example
How it works

Compute a candidate result from an authoritative employee and pin that for this request. Membership is evaluated as of that ; it is not an transaction with HR. In the financial transaction, verify the active policy pointer, lock all applicable budget rows in stable order on one tenant , check settled + reserved + requested <= limit, insert a unique authorization, and update every row atomically. A repeated request returns its stored result only if the payload hash matches. Existing holds retain their original scope and period after an employee transfer.

Walk through an example

A department has $150 remaining and two employees each request $100. The first commits a hold; the second sees $50 remaining and declines. employee counters alone would not enforce the shared department cap.

Failure and recovery

A lost reply is recovered by authorization ID. Monitor lock wait and decline reasons. Isolate a hot tenant and bound concurrency; if necessary use centrally allocated escrow quotas whose sum stays within the limit, accepting stranded capacity and more complexity.

Why this helps

Two independent allows against the same remaining budget would overspend it.

What you give up

A hot department serializes on a budget row; preserve the hard guarantee before adding more throughput.

Deep dive 3

Separate authorization from settlement and payment

Model holds, captures, refunds and reimbursable obligations as durable state transitions with provider identities.

Read the explanation and worked example
How it works

Track each authorization’s remaining hold and cumulative captures. Capture moves held money to settled; duplicate events are no-ops. Reversal releases only unused hold; refunds apply the stated budget-credit policy to the original period, never create fresh current-period allowance accidentally. Approval binds the claim revision and creates one payable obligation with an . Provider or status lookup resolves retries.

Walk through an example

A $100 authorization captures $80 and reverses $20. Settled becomes $80 and reserved becomes zero. A repeated $80 capture changes nothing. A reimbursement transfer that timed out stays UNKNOWN under its original payment ID.

Failure and recovery

Expired holds require the processor’s definitive expiry/ contract. Late or larger presentments can exceed the authorized amount; record the actual obligation and an exception, freeze further spend if necessary. The hard-limit guarantee covers new authorizations, not unpreventable external settlement adjustments. Investigate ambiguous payments rather than retrying blindly.

Why this helps

Retries and late events must not consume a budget twice or pay a claim twice.

What you give up

Provider uncertainty can leave money reserved; financial adds operational work.

Deep dive 4

Keep the fast path bounded under failure

Cache immutable bundles, bound rule execution, isolate tenant load and decline when required state is unavailable.

Read the explanation and worked example
How it works

Use a bounded declarative rule set and version-keyed compiled caches. Resolve employee memberships through an authoritative versioned ; reject stale/missing critical context. A tenant’s policy pointer, budget and decision commits have one multi-zone writer. Use per-tenant admission, separate reimbursement workers and alerts for latency, unknown payments and policy-cache misses.

Walk through an example

HR context is unavailable for a newly transferred employee. Decline the live card request within its deadline; queue a reimbursement for review. A manual-review decision is never an indefinitely pending processor authorization.

Failure and recovery

A regional standby must fence the old financial writer and reconcile lost/in-flight processor and payment IDs before resuming. Async replicas imply a recovery gap, so pause approves/transfers until reconstructed; choose cross-region only if the latency/cost meets the agreed . Disable processor offline stand-in unless the business explicitly accepts bounded overspend risk.

Why this helps

A live card request cannot wait for a manager, a slow HR query or a regional election.

What you give up

Fail-closed behavior reduces successful spending during outages; offline processor stand-in must be disabled for strict hard-limit enforcement.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Define hierarchy and reproducible versionsRestrictive defaults can surprise admins; show matched reasons and require explicit authorized exceptions rather than last-rule-wins.
Reserve shared budgets atomicallyA hot department serializes on a budget row; preserve the hard guarantee before adding more throughput.
Separate authorization from settlement and paymentProvider uncertainty can leave money reserved; financial adds operational work.
Keep the fast path bounded under failureFail-closed behavior reduces successful spending during outages; offline processor stand-in must be disabled for strict hard-limit enforcement.

Production scars & failure modes

Failure investigation

Two employees request $100 each while their department has only $150 remaining.

Look for: Inspect the authoritative budget rows, outstanding holds, unique authorization IDs and transaction results.

Recovery and invariant: Serialize the shared budget reservation: allow one request, decline the other, and replay lost responses from the stored decision.

Component / failureImpactRecovery mechanismAlternative / tradeoff
Cache holds an old policyA newly restricted purchase might pass evaluation.Validate the active version at commit; reload and reevaluate on mismatch.Higher cache churn around publication; old versions remain for historical replay.
Concurrent budget requestsIndependent reads both see the same balance.Lock all applicable budget rows and commit one reservation.Hot shared budgets limit throughput.
Provider response lost or region failsA transfer may already exist externally.Fence writers, preserve original IDs and reconcile before retry.Hold funds and reduce availability until evidence arrives.

60-second interview summary

I would separate policy publication, fast card authorization and asynchronous reimbursement. Policies are immutable, effective-dated bundles with explicit scope precedence. Every decision records its rules and employee context so we can explain and reproduce it.

An allow becomes real only when one transaction records the decision and reserves every applicable hard budget. That prevents two concurrent requests from spending the same remaining department balance. Processor events later convert or release holds with idempotent transitions.

Reimbursement approval binds an exact claim revision and creates one payment obligation plus an . Workers reuse its provider identity and reconcile unknown outcomes before retrying. Tenant quotas isolate load. I decline or pause when financial authority is unavailable, trading some spending availability for correct limits and avoiding duplicate payments.

Explain it without looking

Explain define hierarchy and reproducible versions

Reveal answer

Apply non-overridable company guardrails first; combine scoped restrictions with deny winning and all required approvals retained.

Overlapping groups must not produce an answer that depends on evaluation order.

Restrictive defaults can surprise admins; show matched reasons and require explicit authorized exceptions rather than last-rule-wins.

Explain reserve shared budgets atomically

Reveal answer

Use a tenant-routed transaction for the decision, and all affected hard-limit rows.

Two independent allows against the same remaining budget would overspend it.

A hot department serializes on a budget row; preserve the hard guarantee before adding more throughput.

Explain separate authorization from settlement and payment

Reveal answer

Model holds, captures, refunds and reimbursable obligations as durable state transitions with provider identities.

Retries and late events must not consume a budget twice or pay a claim twice.

Provider uncertainty can leave money reserved; financial adds operational work.

Explain keep the fast path bounded under failure

Reveal answer

Cache immutable bundles, bound rule execution, isolate tenant load and decline when required state is unavailable.

A live card request cannot wait for a manager, a slow HR query or a regional election.

Fail-closed behavior reduces successful spending during outages; offline processor stand-in must be disabled for strict hard-limit enforcement.

Revision checklist

Revision checklist

  • Reconstruct define hierarchy and reproducible versions: Apply non-overridable company guardrails first; combine scoped restrictions with deny winning and all required approvals retained.
  • Reconstruct reserve shared budgets atomically: Use a tenant-routed transaction for the decision, and all affected hard-limit rows.
  • Reconstruct separate authorization from settlement and payment: Model holds, captures, refunds and reimbursable obligations as durable state transitions with provider identities.
  • Reconstruct keep the fast path bounded under failure: Cache immutable bundles, bound rule execution, isolate tenant load and decline when required state is unavailable.
  • 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 live card decisions and asynchronous reimbursement; define policy precedence and what a hard budget guarantees. Estimate 500 peak authorizations/s.
15–30 minHigh-level designTrace publication → evaluation → reserve → processor response, then capture. Draw the separate approval → → payment path.
30–45 minDeep divesDemonstrate overlapping scopes, two $100 requests against $150 remaining, and an unknown reimbursement transfer.
45–55 minFailure and recoveryExplain late captures, a stale policy cache and regional . Name the availability tradeoff and deliver the one-minute synthesis.
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. End-to-end flow
  9. High-level design component walkthrough
  10. Deep dives — decisions, failures and recovery
  11. Tradeoffs and alternatives
  12. Production scars & failure modes
  13. 60-second interview summary
  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