Expense and Spend Management Rules Engine
Two employees request $100 each while their department has only $150 remaining.
Topic tools
Layout updated
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 owner | Minimal 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 service | Expense 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 / input | Response and retry contract |
|---|---|
POST/v1/policies/{id}/versions | 201 immutable candidate bundle with scopes, rules and effectiveAt; validate conflicts and bounded rule complexity. |
POST/v1/policies/{id}/publish | 200 activate validated bundle with expectedActiveVersion; 409 for stale admin edit. Version and activation pointer commit together. |
POST/v1/card-authorizations | 200 allow/decline and reasons after decision + reservation; processor request ID deduplicates. This endpoint evaluates and reserves together. |
POST/v1/expenses | 201 claim revision with amount, currency, occurredAt and receipt references; -Key returns the same claim for the same payload. |
POST/v1/expenses/{id}/approve | 202 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
- Configure policiesAdmin apps, policy , and compiled policy bundles
- Decide card authorizationCard processor, eligibility context, and authorization service
- Reserve and settleTenant financial , reservations, and settlement workers
- 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.
- Edge
- Compute
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 13 flow steps
End-to-end flow
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.
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.
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.
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.
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 .
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
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
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
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
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
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
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
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
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
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
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.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Define hierarchy and reproducible versions | Restrictive defaults can surprise admins; show matched reasons and require explicit authorized exceptions rather than last-rule-wins. |
| Reserve shared budgets atomically | A hot department serializes on a budget row; preserve the hard guarantee before adding more throughput. |
| Separate authorization from settlement and payment | Provider uncertainty can leave money reserved; financial adds operational work. |
| Keep the fast path bounded under failure | Fail-closed behavior reduces successful spending during outages; offline processor stand-in must be disabled for strict hard-limit enforcement. |
Production scars & failure modes
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 / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Cache holds an old policy | A 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 requests | Independent 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 fails | A 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
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope live card decisions and asynchronous reimbursement; define policy precedence and what a hard budget guarantees. Estimate 500 peak authorizations/s. |
| 15–30 min | High-level design | Trace publication → evaluation → reserve → processor response, then capture. Draw the separate approval → → payment path. |
| 30–45 min | Deep dives | Demonstrate overlapping scopes, two $100 requests against $150 remaining, and an unknown reimbursement transfer. |
| 45–55 min | Failure and recovery | Explain late captures, a stale policy cache and regional . Name the availability tradeoff and deliver the one-minute synthesis. |
| 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
- End-to-end flow
- High-level design component walkthrough
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 60-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough