Design a Budgeting App – Frontend System Design

We’ll walk through the frontend system design for a personal budgeting app like YNAB: a web app where a household tracks every transaction, assigns money to categories each month, and sees what is left to spend. You’ll see why the browser’s IndexedDB is the source of truth instead of the server, why money is never a float, how the envelope math stays instant with ten years of history, and how two partners editing the same transaction on two offline phones end up with the same numbers.
This question looks like CRUD. It isn’t. The interviewer is waiting to see whether you notice three traps: floating-point money, totals that are recomputed from all history on every keystroke, and a sync story that silently loses someone’s edit to a dollar amount.
Problem Statement
Design the frontend for a personal budgeting web app like YNAB or Mint.
Requirements:
- Accounts (checking, savings, credit cards, cash) with a transaction register
- Envelope budgeting: assign money to categories each month and see what is available
- Import transactions from linked banks and from CSV files
- Recurring transactions such as rent and subscriptions
- Reports, for example spending by category
- Works offline, on several devices, and for a shared household budget
Describe the client architecture, the data model, money handling, and the sync protocol.
Interviewers are checking three things. Can you represent money exactly? Can you design a local-first client where the UI never waits on the network? And can you explain what happens when two offline edits to the same amount meet on the server?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Envelope budgeting (YNAB) or passive tracking (Mint)? | Envelope. Every dollar gets assigned to a category. |
| 2 | How much history does a heavy user have? | About 10 years, roughly 50,000 transactions. |
| 3 | Must it work fully offline? | Yes. Enter transactions on a flight and sync later. |
| 4 | How many people share one budget? | Usually 1–2 adults, each with a phone and a laptop. |
| 5 | One currency per budget, or many? | One currency per budget. Any ISO 4217 currency. |
| 6 | Do we build the bank connection ourselves? | No. Use an aggregator like Plaid. |
Question 3 decides the architecture: offline writes mean the client needs its own database and a queue of pending changes, not a cache. Question 4 means conflicts are rare but real, and they involve money, so “last write wins” is not good enough for every field. Question 5 tells you that “two decimals” is a bug waiting to happen, because the Japanese yen has zero and the Kuwaiti dinar has three.
Requirements
Functional
- Record transactions with payee, date, amount, category, memo, and cleared status. Split one across several categories.
- Assign money to categories per month. Show assigned, activity, and available, plus “Ready to Assign”.
- Import from linked banks and CSV files without duplicates. Schedule recurring transactions.
- Search and filter the register by payee, memo, category, account, and date range.
- Charts of spending by category, and a shared household budget where every member sees the same numbers.
Non-Functional
- Every interaction reads and writes locally. No spinner, online or offline.
- Exact money: totals match to the cent (or yen, or fils) on every device.
- No lost writes. An offline edit survives a tab close, a crash, and a browser restart.
- The budget screen updates within one frame of an edit, even with 50,000 transactions.
- Bank tokens never reach the browser. Forms and tables work with a keyboard and a screen reader.
Napkin Math
| Metric | Estimate | Calculation | So what? |
|---|---|---|---|
| Transactions per heavy user | ~50,000 | ~400 / month × 120 months = 48,000 | Too many to sum on every render |
| Local data size | ~15 MB | 50,000 × ~300 B per record | Fits easily in IndexedDB quota |
| Budget cells | ~6,000 | 50 categories × 12 months × 10 years | Monthly summaries are tiny. Compute from these. |
| Daily sync payload | ~5 KB | ~15 changes × 300 B | Pull on open and on a poke. No streaming needed. |
| Devices per budget | 2–6 | 2 adults × phone + laptop, maybe a tablet | Offline edits will occasionally collide |
| Largest exact integer | ~$90 trillion | 253 − 1 cents ≈ 9.0 × 1015 cents | A JS number of cents is safe for personal finance |
The numbers say this is not a scale problem. It is a correctness problem. 15 MB is nothing for a browser, but summing 50,000 rows on every keystroke, or rounding $0.01 wrong across a split, is visible to the user immediately.
Architecture
The client is local-first. The UI reads from IndexedDB through a small repository layer and never calls the sync API directly. A sync engine runs in the background, pushing local changes and pulling remote ones.
| Layer | Owns | Runs on | Talks to |
|---|---|---|---|
| UI (views) | Budget grid, register, reports, import wizard | React, main thread | View models only |
| View models | Memoized selectors, commands, money formatting | Main thread | Repository |
| Repository | Typed reads, atomic writes, change events | Main thread + workers | IndexedDB |
| Sync engine | Outbox push, cursor pull, conflict handling | One leader tab | Repository, sync API |
| Workers | CSV parsing, full-text search | Dedicated Web Worker | IndexedDB directly |
| Service Worker | Offline app shell | Service Worker | Cache Storage |
“The browser database is the source of truth for the UI. The server is the source of truth for sync. Every write lands in IndexedDB first, together with an outbox entry, in one transaction. The network only ever moves outbox entries and change log pages.”
Components never open IndexedDB. They call transactions.update(id, patch) and subscribe to queries. That keeps the storage engine swappable (SQLite compiled to WebAssembly on the Origin Private File System is the common alternative) and gives you one place to enforce invariants like “split lines add up to the total”.
Data Model
Every synced record carries the same metadata: an id created on the client, a server-assigned version, a server timestamp, and a tombstone flag. Deletions are tombstones, never hard deletes, so a device that was offline for a week still learns that a record is gone.
type Id = string; // UUIDv7, generated on the client
type Minor = number & { readonly __brand: "Minor" }; // integer minor units: cents, yen, fils
type CurrencyCode = string; // ISO 4217, e.g. "USD", "JPY"
type MonthKey = `${number}-${string}`; // "2026-10"
type CalendarDate = string; // "2026-10-31", no time zone
interface Synced {
readonly id: Id;
readonly budgetId: Id;
version: number; // server change-log position, 0 until first ack
updatedAt: string; // server time, ISO 8601
deleted: boolean; // tombstone
}
interface Assignment extends Synced { categoryId: Id; month: MonthKey; assigned: Minor } // id = `${categoryId}:${month}`
interface SplitLine { categoryId: Id; amount: Minor; memo: string }
interface Transaction extends Synced {
accountId: Id;
date: CalendarDate;
amount: Minor; // negative = outflow
payee: string;
memo: string;
categoryId: Id | null; // null when split or uncategorized
splits: SplitLine[] | null; // sum(splits.amount) === amount
cleared: "uncleared" | "cleared" | "reconciled";
importId: string | null; // dedupe key from the bank or CSV row
scheduleId: Id | null;
catKeys: string[]; // derived: `${categoryId}|${date}` per line, for indexing
payeeLower: string; // derived, for prefix search
}
interface PendingMutation { // outbox row, local only
id: Id; // idempotency key
seq: number; // local order
table: "transactions" | "assignments" | "categories" | "accounts" | "schedules";
recordId: Id;
baseVersion: number;
changes: Record<string, unknown>;
status: "pending" | "inflight" | "conflict";
attempts: number;
}
Four choices in that model are worth defending.
Client-generated ids. A transaction created offline needs an id right away, because split lines, the outbox, and the UI reference it. UUIDv7 is time-ordered, so it also sorts well in an index.
Calendar dates, not timestamps. A coffee bought at 11pm on October 31 in San Francisco is an October expense. Store "2026-10-31", not 2026-11-01T06:00:00Z, or the month boundary moves depending on who looks.
Assignments as their own rows. “Groceries in October has $500 assigned” is one record keyed by categoryId:month, so the budget grid loads a month without touching transactions.
Version from the server. The change log gives every accepted write a monotonically increasing version per budget. It doubles as the pull cursor and the base version for conflict detection. Client clocks are never trusted for ordering.
Money Math Deep Dive
Start this section by saying the sentence the interviewer wants to hear: money is never a binary float. In JavaScript, 0.1 + 0.2 is 0.30000000000000004, and (1.005).toFixed(2) is "1.00" because 1.005 is stored as 1.00499999…
IEEE 754 doubles can’t represent most decimal fractions exactly. Each error is tiny, but a balance is a sum of thousands of values. Integers below 253, on the other hand, are exact.
Integer minor units are the practical default. Decimal strings ("12.34") are also exact and work well on the wire, but you need a decimal library to do math on them. BigInt is unbounded but isn’t JSON-serializable. $12.34 is 1234. ¥1,234 is 1234, because JPY has zero decimal places in ISO 4217. 1.234 KWD is 1234, because the Kuwaiti dinar has three. YNAB’s public API uses the same idea at a finer grain: amounts are integer “milliunits”, where 1000 means one unit of currency.
The minor-unit exponent comes from the currency, never from a hard-coded 100. The browser already ships the table:
Put formatting in a small money module shared by every screen.
- Minor digits come from
Intl.NumberFormat(..., { style: "currency", currency }).resolvedOptions().maximumFractionDigits: 2 for USD and EUR, 0 for JPY, 3 for KWD. - Formatting divides the integer by 10digits and formats with
currencySign: "accounting", so a negative USD amount reads($12.34). The same 1234 renders as$12.34in en-US and¥1,234in ja-JP, and 123456 EUR renders as1.234,56 €in de-DE. - Formatters are cached in a map keyed by
locale|currency.
Dividing by a power of ten for display is fine: the float lives for one format call, and all arithmetic stays in integers. Cache formatters, because constructing an Intl.NumberFormat costs far more than calling format. The browser’s data comes from CLDR, which matches ISO 4217 for almost every currency, so keep the server’s currency table as the source of truth.
Parsing what the user types
Parsing is the mirror image, and it is where locale bugs hide. A German user types 12,50. An American types 1,250. Ask the formatter for the locale’s separators and reject input with more decimals than the currency allows, instead of silently rounding.
The parseMoney function in the same module takes the raw string, the currency, and the locale, and returns integer minor units or null.
- It reads the locale’s group and decimal separators from
formatToParts, strips group separators, and normalizes the decimal separator. - It rejects anything that isn’t an optional sign, digits, and an optional fraction.
- It rejects more fraction digits than the currency allows.
"12.345"in USD is an error, not $12.35. - It rejects results outside the safe integer range.
Returning null instead of throwing keeps the cell editable. The view model shows an inline error and never writes a guess.
Show the parsed value formatted back on blur (“$1,250.00”). That makes an ambiguous entry visible before it is saved.
Splitting without losing a cent
Split $100.00 three ways and each share is 3333.33… cents. Round each one and you get 3333 × 3 = 9999. A cent disappeared. The fix is the largest remainder method: give every part its floor, then hand the leftover units to the parts with the largest remainders.
An allocate(total, weights) function owns this. It takes a total in minor units and a list of non-negative integer weights, and returns parts that always sum to exactly the total. It works on the absolute value and reapplies the sign at the end, so refunds split the same way as purchases. It rejects an empty weight list, non-integer weights, and all-zero weights, because each of those has no correct answer. Splitting $100.00 by [1, 1, 1] gives [3334, 3333, 3333]. Splitting $99.99 by [50, 30, 20] gives [4999, 3000, 2000].
Ties break by position, so every device produces the same split. If two clients rounded differently, they would sync different amounts for the same action. For extreme totals, the intermediate product of total and weight can pass 253, so switch to BigInt there.
Envelope Budgeting and Derived Data
Envelope budgeting has one core formula per category per month:
available = carryover + assigned + activity
Activity is the signed sum of that category’s transactions in the month, so spending makes it negative. Written with spending as a positive number, it is the familiar available = assigned − spent + carryover. Carryover is last month’s available, with one product rule: a common choice (and YNAB’s behavior for cash overspending) is that a negative available resets to zero next month and is subtracted from next month’s Ready to Assign instead.
The bottom half of the split diagram shows it. Groceries has $80.00 left in January, so February starts with $80.00. February overspends by $30.00, so March starts at zero and Ready to Assign drops by $30.00.
Don’t recompute from history
The naive implementation filters 50,000 transactions on every render, and because carryover depends on every previous month, it touches all history. Instead, keep a derived monthSummaries store: one row of activity per (month, category). Update it in the same IndexedDB transaction as the write that changed it.
An activityDeltas(before, after) function owns this. It takes the old version of a transaction (or null on create) and the new one (or null on delete), and returns a small map from month|categoryId to a signed change in activity. It subtracts every split line of the old version and adds every split line of the new one, skipping deleted transactions and off-budget accounts. A transaction with no splits counts as one line for its category. The result is usually one or two entries.
Because the function only diffs two versions, moving a transaction from October to November, changing its category, or splitting it all go through the same code path. Apply remote changes through the same function so local and synced edits can’t drift apart.
Carryover still chains across months, but now it chains across 6,000 small summary cells, not 50,000 transactions. For each category, walk the months forward from the earliest edited one: available = carry + assigned + activity, record any negative as overspending, then set carry = Math.max(0, available). That is a tight integer loop that finishes in well under a millisecond.
Ready to Assign for a month is income so far, minus everything assigned so far, minus overspending from earlier months. All of it comes from summaries.
Memoized selectors
The budget grid shows about 50 rows. When one transaction changes, at most a few rows should re-render. The view model publishes new cell objects only for cells whose values changed. Each row subscribes to its own cell with useSyncExternalStore, and a row wrapped in React.memo skips rendering when its cell reference is unchanged.
Charts
“Spending by category this month” is 50 activity cells, already computed. A 12-month trend is 600. Charts read from summaries, never from the transaction store. Render SVG bars sorted by amount, fold the long tail into “Other”, and use notation: "compact" for axis labels like “$1.2K”.
Local-First Storage and Sync Deep Dive
IndexedDB schema and indexes
The register must filter 50,000 transactions by account, category, and date range instantly. That means indexes, not getAll() plus Array.filter.
The repository owns the schema. Five object stores cover the app.
transactionskeyed by id, with indexesbyAccountDateon["accountId", "date"],byDate, a multiEntrybyCatKeyon values like"catId|2026-10-31", a uniquebyImportIdon["accountId", "importId"], andbyPayeeon the lowercased payee.assignmentskeyed by id, indexed by month.monthSummarieskeyed bymonth|categoryId.outboxwith an auto-increment sequence, indexed by record id for coalescing.metafor the cursor, client id, and schema info.
Schema changes go through a versioned upgrade that migrates step by step from the user’s old version. Fresh installs create everything at once. A query like “October for one account, newest first” is a single reverse cursor over byAccountDate bounded by [accountId, "2026-10-01"] and [accountId, "2026-10-31"].
Three IndexedDB details make this schema work:
- Compound indexes on
["accountId", "date"]give you “this account, this date range, sorted” in one range query. - A multiEntry index on
catKeysindexes each split line separately. A transaction split across Groceries and Household shows up in both categories’ ranges, which a singlecategoryIdfield can’t do. - Invalid keys are skipped.
nullis not a valid IndexedDB key, so manual transactions withimportId: nullare left out ofbyImportId, and the unique constraint only applies to imported rows.
Paginate the register with keyset cursors ([date, id] of the last row) and render it with a virtualized list. IndexedDB has no full-text search. Payee prefix search uses IDBKeyRange.bound(q, q + "uffff") on byPayee. Memo search runs in a worker that walks byDate newest first and stops after 100 matches.
Every write is one atomic transaction
A local edit writes the record, the outbox entry, and the summary deltas in one readwrite transaction. Either all three commit or none do. Split them, and a crash in between leaves an edit that never syncs.
After commit, the repository emits a change event and posts it on a BroadcastChannel so other tabs refresh. Only one tab runs the sync engine, elected with the Web Locks API: every tab calls navigator.locks.request("sync-leader", ...), and the holder syncs until it closes.
The outbox
Each pending mutation moves through a small state machine. It starts as pending in IndexedDB. The sync engine marks a batch inflight and pushes it. The server answers per mutation: applied, conflict, or rejected. A timeout or a 5xx sends it back to pending with exponential backoff and jitter.
Retries are only safe because every mutation has an id. The server records processed mutation ids, so a push whose response was lost is acknowledged again instead of applied twice. Without that, a retried “assign +$50 to Groceries” assigns $100. Coalesce before sending: five offline edits to one memo become one mutation, as long as none is in flight.
Push, pull, and conflicts
One sync cycle pushes first, then pulls everything since the saved cursor.
The sync engine runs only in the leader tab and does two phases per cycle.
- Push. Take up to 100 outbox rows, mark them inflight, and send them with the client id. For each result: applied drops the row and records the new version, conflict keeps the row and flags the record, rejected drops the row and surfaces an error.
- Pull. Request pages of up to 500 changes since the saved cursor until the server says there are no more. Each page is applied (records, summaries, and the new cursor) in one IndexedDB transaction.
Pushing first means the pull already includes the server’s view of our own writes, so the client never has to reconcile an echo against a stale local copy. A network failure in either phase just ends the cycle. The next trigger starts over safely, because both phases are idempotent.
Two rules keep this correct. First, save the cursor in the same IndexedDB transaction as the changes it covers, so a crash replays a page instead of skipping one. Second, when a remote change arrives for a record with a pending local mutation, apply every field except the ones the local mutation changes, or the field flickers. The Figma design uses the same “unacked write wins locally” rule.
Conflict detection happens on the server, per field. For each changed field, the server checks whether someone else changed that field after the mutation’s baseVersion. If not, it applies the field. Sam fixing the memo while Alex fixes the amount is not a conflict.
| Field | Concurrent edit rule | Why |
|---|---|---|
| Memo, payee, category, cleared | Last write wins, server order | Low stakes, easy to fix |
| Amount, date, account | Conflict: ask the user | Changes balances. Silent loss is unacceptable. |
| Monthly assignment | Send deltas, server adds them | “+$50” and “+$100” commute |
| Delete vs edit | Delete wins, offer undo | A tombstone must not be resurrected |
| Reconciled transaction | Reject edits | Reconciled history is locked |
“Last write wins” here means the server’s arrival order, recorded as version and updatedAt. A phone with its clock set a day ahead would otherwise win every argument.
If both partners add money to Groceries offline, last write wins on the absolute value loses one of them. “Move money” is naturally a delta, so send it as assignDelta and let the server add.
On an amount conflict, the client keeps its local value, flags the transaction, and shows both inline: “Sam changed this to $45.50. Keep $54.00 or use $45.50?” The choice becomes a new mutation based on the server’s current version.
Multi-device and shared budgets
A household budget is one change log with several members. Each device keeps its own cursor and outbox, and the server authorizes every mutation against budget membership.
For near-real-time updates, the server sends a data-free poke over a WebSocket, { type: "poke", version: 19 }, and the client pulls if that is ahead of its cursor. A missed poke costs latency, never correctness. Sync also runs on app open, on the online event, and when the tab becomes visible. A new device downloads a snapshot with its cursor instead of replaying ten years of change log.
Imports and Recurring Transactions
Bank aggregation is a server concern
Plaid’s flow keeps secrets off the client by design. Your server creates a link_token, the browser opens Plaid Link with it, and the user logs in to their bank inside Plaid’s UI. Link returns a short-lived public_token, which the server exchanges for an access_token and stores encrypted. The browser never sees it.
The server then pulls new transactions with Plaid’s cursor-based /transactions/sync endpoint when a webhook says updates are available, and writes them to the change log. Clients get them through the normal pull, with no bank-specific code.
Normalize on the server. Plaid reports money leaving the account as a positive amount, so flip the sign. Posted transactions replace pending ones (often with a new amount after a tip) and reference them with pending_transaction_id, so update the existing record instead of adding a second one.
CSV import in a worker
CSV import is fully client-side. A 5,000-row export is about 500 KB, small to read but slow enough to parse and dedupe that it shouldn’t run on the main thread. Send the File to a dedicated worker, which can parse it and write to IndexedDB directly. Splitting on commas is not a parser: follow RFC 4180 for quoted fields, "" escapes, and CRLF line endings, and strip a leading byte order mark.
- Show the first 20 rows and let the user map columns (date, payee, amount, or separate inflow and outflow columns).
- Ask for the date format.
03/04/2026is March 4 in the US and April 3 in most of Europe. - Parse amounts with
parseMoneyusing the file’s locale, not the user’s. Semicolon-delimited files with decimal commas are common in Europe. - Build an
importIdfrom date, amount, normalized payee, and an occurrence counter, so two identical $4.50 coffees on one day both import, but re-importing the file adds nothing. - Write a few hundred rows per IndexedDB transaction, each batch with its outbox entries and summary deltas.
Recurring transactions
A schedule stores a template transaction, a rule (monthly on the 1st, every 2 weeks), and the next due date. Upcoming instances show as muted, read-only rows. When the due date arrives, the client turns the instance into a real transaction. Clamp monthly rules to short months: “the 31st” means February 28 (or 29), not March 3.
The trap: two offline devices both see that rent is due and both create it. Derive the instance id from the schedule id and the occurrence date (a UUIDv5 or a hash of scheduleId + date). Both devices create the same record, and the second create is an idempotent upsert instead of a duplicate rent payment.
Offline Shell and Storage Durability
The Service Worker’s only job is the app shell: precache HTML, JS, CSS, and fonts, serve them cache-first, and update in the background. Don’t cache API responses in Cache Storage. IndexedDB already is the data cache. The Background Sync API can flush the outbox after the tab closes, but only Chromium-based browsers support it, so treat it as a bonus.
Browser storage is “best effort” by default, so the browser may evict it under storage pressure. Call navigator.storage.persist() after the user’s first real edit, and check navigator.storage.estimate() for usage and quota. Chrome grants persistence silently based on engagement. Firefox asks the user. Safari can delete script-writable storage for a site the user hasn’t interacted with for seven days, unless it is installed to the home screen.
The design answer is the same everywhere: the server holds everything that has synced, so eviction costs a re-download. The real risk is the outbox, so warn the user when unsynced changes are older than a day.
Encryption at rest
The browser doesn’t encrypt IndexedDB beyond the operating system’s disk encryption. You can encrypt fields with Web Crypto (AES-GCM with a non-extractable CryptoKey), but it doesn’t stop XSS, since script in your origin can use the same key, and encrypted fields can’t be indexed or range-queried.
A reasonable answer: rely on OS disk encryption, offer an optional passphrase lock for shared computers, and wipe IndexedDB and Cache Storage on logout. Full end-to-end encryption is possible, but then the server can’t import bank data or validate amounts.
State and Data Flow
- The user types
54.00in an amount cell. The view model parses it withparseMoney. Invalid input stays in the cell with an error. - The view model calls
repo.transactions.update(id, { amount }), re-runningallocateif the transaction is split. - The repository writes the record, the outbox mutation, and the
activityDeltasin onereadwritetransaction. - On commit, it emits a change event and broadcasts it to other tabs. Only rows whose cells changed re-render.
- The sync leader wakes on a short debounce, pushes the outbox, and pulls since the cursor.
- Remote changes go through
repo.applyRemote: the same delta code, but no outbox entry.
The UI has one read path and one write path. Whether a change came from this tab, another device, or a bank import, it arrives as a repository change event.
API
// REST (session cookie auth)
POST /api/sync/push // { clientId, mutations } -> { results }
GET /api/sync/pull?budgetId=&since=&limit=500 // -> { changes, cursor, hasMore }
GET /api/budgets/:id/snapshot // first load on a new device: full state + cursor
POST /api/plaid/link-token // -> { linkToken }
POST /api/plaid/exchange // { publicToken } -> { accountIds }; access_token stays on the server
type Mutation = Pick<PendingMutation, "id" | "table" | "recordId" | "baseVersion" | "changes"> & {
op: "upsert" | "delete" | "assignDelta";
};
type MutationResult =
| { id: Id; status: "applied"; version: number; updatedAt: string }
| { id: Id; status: "conflict"; fields: string[]; server: Record<string, unknown>; version: number }
| { id: Id; status: "rejected"; reason: "validation" | "permission" | "reconciled" };
type Change = { table: string; recordId: Id; version: number; updatedAt: string; data: Record<string, unknown> | null };
// Realtime: wss://sync.example.com/budgets/:id
type ServerEvent = { type: "poke"; version: number };
Pull returns full records, not field diffs. Records are around 300 bytes, so whole records keep the client simple. data: null means the record was purged after the tombstone retention window.
Optimizations
| Problem | Technique | Effect |
|---|---|---|
| Totals recomputed from all history | Incremental month summaries | O(1) work per edit |
| Whole budget grid re-renders | Per-row selectors + React.memo |
Only changed rows render |
| 50,000-row register | Virtualized rows, keyset pagination on indexes | Constant DOM size |
| Formatter churn | Cache Intl.NumberFormat per locale and currency |
No construction in render |
| Slow CSV import | Worker parsing, batched IndexedDB transactions | Main thread stays free |
| Chatty sync | Coalesce outbox, batch 100 per push, data-free pokes | Few small requests |
| Slow cold start | Shell from Service Worker, load current month first | Budget visible before the register loads |
Handling Edge Cases
- Time zones. Dates are calendar strings, and “this month” is computed in the user’s local time zone. Never derive a transaction’s month from a UTC timestamp.
- Splits that don’t add up. The repository rejects a write where split lines don’t sum to the total. When the total changes, offer “rebalance proportionally” via
allocateor “put the difference in one line”. - Duplicate imports. The unique
[accountId, importId]index stops duplicates locally. The server enforces the same rule for bank imports. - Schema migrations. Bumping the IndexedDB version fires
versionchangeon other open tabs. Close the connection there and prompt a reload, otherwise the upgrade staysblocked. - Long offline period. If the server has compacted the change log past the client’s cursor, it returns a reset. The client downloads a snapshot and re-applies its outbox on top, so pending edits survive.
- Logout on a shared computer. Delete the database with
indexedDB.deleteDatabase, clear Cache Storage, and refuse to log out silently while the outbox has unsynced changes.
Accessibility and Security
Accessibility
- The register is a real table with a
<caption>and<th scope="col">headers. When virtualized, setaria-rowcounton the table andaria-rowindexon each rendered row so screen readers announce “row 1,204 of 50,000”. - Amount fields are
<input type="text" inputmode="decimal">, nottype="number", which acceptse, changes value on mouse wheel, and handles decimal commas inconsistently. Link format hints and errors witharia-describedby. - Don’t rely on red and green alone for overspent and funded, since red-green is the most common color blindness. Give overspent cells text like “overspent by $30.00”, because parentheses and minus signs are easy to miss when read aloud.
- The budget grid supports arrow-key navigation, Enter to edit, and Escape to cancel. Every chart has a data table alternative.
Security
- Bank access tokens live only on the server, encrypted. The client handles a
link_tokenand a one-timepublic_token, nothing else. - Sessions use an
HttpOnly,Secure,SameSite=Laxcookie plus a CSRF token on state-changing requests. - Set a strict Content Security Policy:
script-src 'self'plus Plaid Link’s origin,frame-srcfor its iframe,object-src 'none', andframe-ancestors 'none'. XSS matters more than usual, because the whole financial history sits in IndexedDB. - Payees and memos from banks and CSV files are untrusted text. Never render them as HTML. On CSV export, escape cells starting with
=,+,-, or@to prevent spreadsheet formula injection. - The server validates every mutation: membership, integer amounts, split sums, and reconciled locks.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| Money | Store dollars, call toFixed(2) |
Integer minor units per ISO 4217, largest-remainder splits, Intl for display |
| Storage | Fetch per screen, cache in Redux | IndexedDB as source of truth behind a repository, UI reads locally |
| Sync | “Send changes when online” | Atomic outbox, idempotent mutation ids, pull since cursor |
| Conflicts | Last write wins by client clock | Per-field merge in server order, user decides amounts, assignment deltas |
| Budget math | Sum all transactions on render | Incremental month summaries, roll forward, memoized row selectors |
| Bank import | Call the bank API from the browser | Aggregator tokens on the server, imports arrive through the change log |
| Offline | “Add a service worker” | Shell in SW, data in IndexedDB, persist(), single sync leader via Web Locks |
Conclusion: How to Design a Budgeting App
Start with money: integer minor units with the exponent from the currency, a largest-remainder split that never loses a cent, and Intl.NumberFormat only at the edges. Then make the browser the source of truth: IndexedDB behind a repository, with every write committing the record, an outbox entry, and the summary deltas in one transaction.
Everything else follows from those two decisions. Envelope math reads from small monthly summaries, so the budget updates in a frame. Sync is an outbox push plus a cursor pull, with idempotent mutation ids and per-field rules that ask a human before an amount is overwritten. If you can explain why 0.1 + 0.2 is not 0.3, why the rent schedule needs a deterministic id, and why the bank token never touches the browser, you’ve shown the interviewer you can build software people trust with their money.
