The Problem#
Most adults have money in several places: a checking account at one bank, a credit card from another, a savings account somewhere else, perhaps a car loan and a retirement account. Each has its own website and its own app. Nobody can answer simple questions such as "how much did I spend on food last month?" or "am I on track this month?" without opening five apps and adding things up by hand.
A personal finance aggregator solves this. The user connects all their financial accounts once. From then on the service pulls their balances and transactions every day, sorts each transaction into a category ("Groceries", "Rent", "Fuel"), shows one dashboard with everything, lets the user set budgets, and warns them when they are close to going over.
Mint was the best-known product of this kind. Its Wikipedia article says it was created by Aaron Patzer, first got its bank connections through a deal with the aggregator Yodlee, was bought by Intuit for $170 million (announced in September 2009, completed in November 2009), could connect to more than 16,000 US and Canadian institutions by 2010, reported over 20 million users in 2016, and was shut down in March 2024, with users pointed to Intuit's Credit Karma. Similar products exist all over the world, and the same plumbing sits under lending apps, accounting tools and payment apps.
The interesting part is not the user interface. It is the plumbing underneath:
- The service does not own the data. Every transaction lives at a bank. The aggregator must fetch it from thousands of different institutions, each with its own technology, outages, login rules and data quirks.
- Credentials are dangerous. To fetch data, the service may need the user's online-banking username and password, or a long-lived access token. If these leak, attackers can see (and sometimes move) people's money. This is a very different problem from storing the service's own login passwords.
- The data changes after you receive it. A card payment first appears as "pending" with one amount and description, then "posts" a day or two later, sometimes with a different amount (a restaurant tip) or a different description. Transactions can be removed or edited by the bank. The sync must be idempotent and must merge updates without creating duplicates.
- Writes dominate reads. Tens of millions of transactions flow in every day, but each user looks at their dashboard only now and then. The system must ingest efficiently and still make dashboards fast.
- Categories and budgets need computation. Every transaction must be categorised, every category total recalculated, every budget checked, and the user notified at the right moment, exactly once.
An analogy. Imagine a personal assistant who has the keys to all your mailboxes. Every morning they visit each mailbox, collect the bank statements, sort every line into labelled folders ("food", "rent", "travel"), update a summary sheet on your desk, and leave a sticky note if you are close to your food budget. The hard parts of that job are exactly the hard parts of this system: the assistant must guard the keys very carefully, visit each mailbox without annoying the post office, avoid filing the same receipt twice when the bank re-sends a corrected statement, and keep the summary sheet up to date so that you can glance at it any time.
Background: a few terms used in this design#
- Financial institution (FI). A bank, credit union, card issuer, broker or lender that holds an account.
- Aggregator (data provider). A company that connects to thousands of institutions on behalf of apps and returns accounts, balances and transactions in one common format. Plaid, Yodlee, MX, Finicity and others play this role. A personal finance app can build connections itself, buy them from an aggregator, or mix both.
- Connection (an "Item" in Plaid's terms). One login at one institution. A single connection can cover several accounts, such as checking, savings and a credit card at the same bank.
- Screen scraping. Logging in to the bank's website as the user, with the user's real username and password, and reading the pages (or the private APIs behind the bank's own app) to extract data. It works almost everywhere, but it needs the user's real password and breaks whenever the bank changes its site.
- OAuth. A standard way for a user to grant an app limited access to their account without giving the app their password. The user logs in on the bank's own page, approves access, and the app receives a token. See Authentication and Authorization.
- Open banking. Rules and standards that require or encourage banks to share customer data with authorised third parties through official APIs, with the customer's consent. Examples include PSD2 in the European Union, the UK's Open Banking programme, Australia's Consumer Data Right and the US rule under Section 1033 of the Dodd–Frank Act.
- AISP (account information service provider). The EU and UK name for a licensed company that reads account data with the user's consent. A Mint-like app in Europe is an AISP, or uses one.
- Pending and posted transactions. A pending transaction has been authorised but not yet settled; its amount and description can still change, and it can disappear. A posted (settled) transaction is final, though banks occasionally correct it later.
- Merchant category code (MCC). A four-digit code that the card networks attach to every merchant, such as 5411 for grocery stores. It helps categorisation, but it describes the merchant's business, not what the user bought.
- Envelope encryption. Encrypt each piece of data with its own data key, then encrypt (wrap) that data key with a master key held in a key management service. See deep dive 2.
- KMS and HSM. A key management service holds master keys and performs wrap and unwrap operations on request. A hardware security module is tamper-resistant hardware that keeps keys inside it; many KMS products store their master keys in HSMs.
- OLAP (online analytical processing). Databases built for large aggregate queries (sum and group-by over millions of rows), usually with columnar storage. Examples are BigQuery, Redshift, Snowflake and ClickHouse. See Data Pipelines, Warehouses and Lakes.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| Which account types do we support? | Investment and loan data have different shapes from bank transactions | Checking, savings and credit cards first; loans and investments as balances only |
| How do we connect to banks: build connections, use an aggregator, or both? | Decides how much connection engineering we own | Use one or more aggregators, plus direct open-banking APIs where they exist; no scraping of our own |
| How fresh must data be? | Drives sync frequency and cost | Daily automatic updates for active users; on-demand refresh when the user asks |
| Who counts as active? | Most of the sync cost goes to users who never look | Users who logged in within the last 30 days get daily updates; others refresh on their next login |
| Can users change a transaction's category? | Overrides must survive later syncs and re-categorisation | Yes; a manual category is never overwritten automatically |
| Do we suggest budgets? | Needs income estimation and templates | Yes; a suggested budget from income, editable per category |
| How fast must budget alerts arrive? | Decides push vs batch evaluation | Within minutes to a few hours of the transaction arriving; not instant |
| Do we move money (pay bills, transfer)? | Moving money adds payment-system risk and regulation | No; read-only. Payments are out of scope |
| How many users and accounts? | Sizing | 10 million users, 30 million linked accounts |
| Which countries? | Open-banking rules, currencies, categories | US first; design for EU and UK rules (consent expiry) as well |
| Do we keep history after a user unlinks an account? | Privacy law and user trust | No; unlinking revokes access, and deleting the account deletes the data |
| Do we use the data for advertising or product offers? | Consent rules restrict secondary use | Only what the user explicitly opts into; analytics on aggregated, de-identified data only |
Requirements#
Functional requirements#
- Link a financial account. A user connects an account at any supported institution, through an OAuth consent screen where the bank offers one, or through the aggregator's login flow otherwise. They can also re-authenticate a broken connection and unlink an account.
- Sync transactions and balances. The service fetches historical transactions when an account is first linked (for example the last 90 days to 2 years), then fetches new and changed transactions every day for active users, and on demand when the user presses "refresh".
- Categorise transactions. Every transaction gets a category automatically. The user can change it, and can create rules ("always put Joe's Café under Coffee"). A manual change is never undone by the system.
- Show spending by category. The user sees monthly spending per category, trends over time, account balances and net worth.
- Budgets. The service suggests a budget from the user's income and spending, and the user can set or change a monthly budget per category.
- Alerts. The service notifies the user when spending in a category nears or exceeds its budget, and for other events such as a large transaction, a low balance or a broken connection.
- Search and filter transactions by date, amount, merchant, account and category.
Out of scope: moving money (bill payment, transfers), credit scores, investment performance analytics, tax filing, shared household accounts (mentioned briefly in the variants deep dive).
Non-functional requirements#
- Security first. Credentials and tokens must never be stored in a form that one stolen database or backup can unlock. Transaction data is encrypted at rest and in transit, and access is logged.
- Correctness of money data. No duplicate transactions, no lost transactions, category totals that match the transactions behind them. A user who sees the same purchase twice stops trusting the whole app.
- High availability for reading. Dashboards should be available 99.9% or better, even when a bank or aggregator is down; in that case show the last known data with a "last updated" time.
- Fast reads. Dashboard p99 under 300 ms; transaction search p99 under 500 ms.
- Efficient writes. Absorb billions of transaction writes per month, with peaks after banks publish overnight postings, without slowing down reads.
- Good-citizen syncing. Respect each institution's and aggregator's rate limits and contracts; never hammer a struggling bank.
- Privacy and consent. Collect only what the product needs, honour revocation immediately, and delete data on request.
- Cost control. Aggregators often charge per connected account or per call, so useless syncs are wasted money as well as wasted load.
Capacity Estimation#
We size for 10 million users with 30 million linked accounts, the scale of a large consumer finance app at its peak. A useful conversion: one month is about 2.5 million seconds (30 × 86,400 = 2.59 million).
Users, connections and accounts.
| Quantity | Assumption | Value |
|---|---|---|
| Registered users | given | 10 M |
| Linked accounts | 3 per user | 30 M |
| Connections (logins) | about 2 accounts per login | 15 M |
| Users active in the last 30 days | 40% | 4 M |
| Connections that get daily automatic sync | active users' connections | about 6 M |
The active-user rule is the single biggest saving in the design. Syncing all 15 million connections every day would cost 2.5 times as much as syncing the 6 million that belong to people who actually look at the app. An inactive user's data is not lost: the bank keeps it, and we fetch it when they return.
Transaction writes. We plan for 5 billion transaction write events a month. This is more than the number of distinct purchases, because each card purchase usually arrives twice (once pending, once posted), and banks send corrections and removals.
- Average write rate: 5 B / 2.5 M s ≈ 2,000 writes per second.
- New distinct transactions: about 60 per account per month × 30 M accounts ≈ 1.8 billion a month.
- Peak: banks post overnight batches, and aggregators deliver many updates in the early morning. Plan for 5× the average in the morning window: 10,000 writes per second.
Reads. Users look much less often than data arrives: about 500 million read requests a month, so 500 M / 2.5 M s ≈ 200 reads per second on average, perhaps 1,000 per second in the evening peak. Writes outnumber reads by about 10 to 1. This is unusual for a consumer app and shapes the design: the write path must be cheap and asynchronous, and reads must be served from precomputed aggregates.
Storage for transactions. A minimal transaction (user id 8 bytes, date 5 bytes, seller 32 bytes, amount 5 bytes) is about 50 bytes. With 5 billion a month that gives 250 GB a month and 9 TB in three years. That is a useful floor, but a real row carries more:
| Field | Bytes (approx.) |
|---|---|
| Ids: transaction, account, user, source id from the aggregator, pending link | 80 |
| Dates (authorised, posted), amount, currency, status flags | 30 |
| Raw description from the bank | 60 |
| Merchant id, category id, category source, confidence | 30 |
| User note, user category, timestamps, version | 50 |
| Row overhead and indexes | 350 |
| Total | about 600 |
Stored distinct transactions: 1.8 B a month × 600 bytes ≈ 1.1 TB a month, so about 40 TB over three years before replication, or 120 TB with three copies. Raw payloads from the aggregator (about 1.5 KB of JSON each, around 300 bytes after compression) are kept in object storage for re-processing: 1.8 B × 300 B ≈ 540 GB a month.
Sync jobs.
| Source of sync work | Per day |
|---|---|
| Daily automatic sync of active connections | 6 M |
| On-demand refreshes ("pull to refresh", new login) | 1 M |
| Webhook-triggered delta pulls (the aggregator found new data) | 6 M |
| Total | about 13 M a day, about 150 per second on average |
A sync call to an aggregator or bank is slow: a delta pull usually takes 0.5–3 seconds, and a fresh login that the aggregator performs against a bank can take 10–30 seconds. With Little's law (jobs in flight = arrival rate × time per job), 150 jobs per second × 3 seconds ≈ 450 jobs in flight on average. If most automatic syncs are squeezed into a six-hour morning window, the rate rises to about 400 per second and in-flight jobs to about 1,200. That number sets the size of the sync worker pool and, more importantly, the concurrency we need from each aggregator.
Credential vault. 15 M connections × about 2 KB (encrypted token or credential, wrapped data key, metadata) ≈ 30 GB. Tiny in bytes, enormous in importance.
Aggregates. Monthly spending rows: about 10 non-empty categories per user per month × 10 M users × 36 months ≈ 3.6 billion rows at about 50 bytes ≈ 180 GB. Budgets: 10 categories × 10 M users = 100 M budget items if stored in full, but we store only the user's changes against a template (see deep dive 6), which is far fewer.
Category dictionary. A starter map of the 50,000 most common sellers, with about 255 bytes per entry, is about 12 MB, small enough to hold in memory in every categorisation worker. The real merchant table, after normalising messy bank descriptions, has millions of merchants and many more description variants, so it lives in a database with a hot in-memory cache.
Notifications. If each active user receives about one alert a week, that is 4 M / 7 ≈ 600,000 a day, about 7 per second. Small, but each must be sent exactly once.
Network. Ingest: 1.8 B transactions × 1.5 KB ≈ 2.7 TB a month, about 1 MB/s on average. Reads: 500 M responses × 20 KB ≈ 10 TB a month, about 4 MB/s on average. Neither is a challenge; the bottlenecks are database writes, per-institution rate limits and aggregator latency.
Cost reasoning. Aggregators charge for access, usually through subscriptions per connected account and per-request fees for extras such as forced refreshes. With an assumed price of one cent per forced refresh, 1 million on-demand refreshes a day would cost $10,000 a day, or more than $3.5 million a year. That is why the design rate-limits "refresh" per user and shows cached data first.
Core Entities#
- User. The person using the app: id, email, password hash (for our own login), country, time zone, income tier, preferences.
- Institution. A bank or other provider: id, name, country, how we connect (direct open-banking API, aggregator A, aggregator B), current health.
- Connection. One login at one institution for one user: status (
ACTIVE,NEEDS_REAUTH,ERROR,REVOKED), provider, provider's item id, consent expiry, last successful sync, sync cursor. - Credential. The secret that lets us read data for a connection: an OAuth access and refresh token, or an aggregator access token. Stored only in the credential vault, encrypted, never in the main database.
- Account. A financial account under a connection: type (checking, savings, credit card, loan, investment), masked number, currency, current and available balance.
- Transaction. One money movement: amounts, dates, raw description, pending flag, merchant, category, and the source ids needed for deduplication.
- Merchant. A normalised business ("Starbucks"), with a default category, logo and the description patterns that map to it.
- Category. A node in a two-level taxonomy (for example "Food and Drink" > "Coffee").
- Rule. A user's own categorisation rule ("merchant X goes to category Y").
- Budget. A monthly limit per category for a user, possibly from a template with overrides.
- Monthly spending. A precomputed aggregate: user, month, category, total, count.
- Alert. A notification event: type, trigger, the key that makes it fire once, delivery status.
- Consent. What the user allowed, for which purpose, when it was granted and when it expires or was revoked.
API Design#
# Linking accounts
POST /v1/link/sessions {institution_id?} -> {link_token, expires_at}
POST /v1/connections {public_token, institution_id}
-> {connection_id, accounts[]}
GET /v1/connections -> [{id, institution, status, last_synced_at}]
POST /v1/connections/{id}/refresh Idempotency-Key: <uuid> -> 202 {sync_job_id}
POST /v1/connections/{id}/reauth -> {link_token}
DELETE /v1/connections/{id} -> 204 (revokes and deletes data)
# Reading money data
GET /v1/dashboard -> {net_worth, balances[], month_spend, budgets[], stale_connections[]}
GET /v1/accounts -> [{id, type, mask, balances}]
GET /v1/transactions?account_id=&from=&to=&category=&q=&cursor=&limit=50
-> {items[], next_cursor}
PATCH /v1/transactions/{id} {category_id?, note?, hidden?, if_version}
-> {transaction}
# Categories, rules and spending
GET /v1/categories
POST /v1/rules {match: {merchant_id | text}, category_id, apply_to_past}
GET /v1/spending?month=2026-11&group_by=category
-> [{category, amount, count, budget}]
GET /v1/trends?months=12&category=
# Budgets and alerts
GET /v1/budgets?month=2026-11
PUT /v1/budgets/{category_id} {amount, rollover?}
GET /v1/budgets/suggestion -> {income_estimate, items[]}
PUT /v1/alerts/preferences {budget_thresholds: [0.8, 1.0], large_txn: 500, channels}
# Inbound from aggregators (signed, internal ingress only)
POST /internal/webhooks/{provider} {item_id, event, ...} -> 200Design notes:
- The link flow never sends credentials through our main API. The browser or app opens the bank's OAuth page or the aggregator's hosted login widget, and our servers only receive a short-lived public token, which the backend exchanges for a long-lived access token server to server. Our web servers never see a bank password.
- Refresh is asynchronous.
POST /refreshreturns202 Acceptedwith a job id. The app shows cached data immediately and updates when the job finishes, through a push message or by polling the job. The idempotency key stops a user tapping "refresh" five times from creating five jobs, and a per-user limit (for example one forced refresh per connection per 15 minutes) caps aggregator cost. - Cursor pagination for transactions. Transaction lists are long and change while the user scrolls (new transactions arrive, pending ones post). An opaque cursor on (date, id) keeps pages stable, unlike page numbers.
if_versionon edits. A user editing a transaction on two devices, or editing while a sync updates the same row, could overwrite one change with another. The client sends the version it saw, and the server rejects the update if the row has moved on (optimistic concurrency; see Concurrency Control and Database Locking).- Webhooks are verified and cheap. The webhook handler checks the provider's signature, records the event and enqueues a sync job; it does no fetching itself, so a burst of webhooks cannot exhaust request threads (see Polling, Long Polling, SSE, WebSockets and Webhooks).
- Deletion is a real API.
DELETE /connections/{id}revokes the token at the provider, deletes the credential, and schedules deletion of the connection's data. Consent rules in many countries require this to be simple.
High-Level Design#
We build the design one requirement at a time, then put the pieces together.
1) Users can link a financial account#
The safest way to link an account is one where our servers never see the bank password. Two paths achieve that:
- Bank OAuth (open banking). The user is sent to the bank's own login page, logs in there (often with the bank's multi-factor check), and approves "share my accounts and transactions with this app". The bank redirects back with an authorisation code, and the aggregator or our connector exchanges it for an access token and a refresh token.
- Aggregator-hosted login. For banks without an API, the aggregator's widget (for example Plaid Link) shows the bank's login form inside the aggregator's own secure page. The aggregator holds the credentials and does the scraping. We receive only a token that identifies the connection at the aggregator.
Either way, the app ends up with a short-lived public token, which our backend exchanges for a long-lived access token in a server-to-server call. The access token goes straight into the credential vault; the main database only stores a reference to it.
The Connection Service then lists the accounts under the connection, stores them, and queues an initial sync that fetches history (for example 90 days at once, then up to 2 years in the background).
2) The service syncs transactions periodically and on demand#
Sync work comes from three triggers:
- Scheduled. A Sync Scheduler creates one job per active connection per day, spread across the day rather than all at midnight.
- On demand. The user taps refresh, or opens the app after a long absence.
- Provider push. The aggregator sends a webhook saying "new data is available for connection X". Many aggregators poll banks themselves; Plaid's documentation, for instance, says it checks for new transactions between one and four times a day depending on the institution and fires a
SYNC_UPDATES_AVAILABLEwebhook when it finds changes.
All three put jobs on the same Sync Queue. Sync Workers take a job, fetch the token from the vault, call the provider through a Connector Gateway (which knows each provider's API and enforces per-institution rate limits), and pull only the changes since the last cursor. They write the raw response to object storage first, then normalise it into the common transaction format and upsert it into the Transaction Store.
Writing raw payloads before parsing has a big benefit: when the parser has a bug, or the categoriser improves, we can re-process the stored raw data without calling the bank again.
3) Transactions are categorised#
A Category Service consumes "transaction added or changed" events. For each transaction it:
- Normalises the merchant from the messy bank description ("SQ *JOES CAFE 1234 SEATTLE WA" becomes merchant "Joe's Café").
- Applies the user's own rules first ("Joe's Café is always Coffee").
- Otherwise uses the merchant's default category from the merchant dictionary (seeded with the most popular sellers), the provider's category if it is confident, the MCC, and a machine-learning model for the rest.
- Never touches a transaction whose category the user set by hand.
It writes the category back to the transaction and emits a "categorised" event.
4) Budgets and alerts#
A Budget Service consumes "categorised" events and keeps a monthly spending table up to date: for each (user, month, category) the total and count. When a total crosses a threshold of the user's budget (for example 80% and 100%), it emits an alert event, which the Notification Service turns into a push notification or email. Budgets themselves come from a template based on income (for example housing 40%, food 20%, transport 10%, shopping 20%) plus the user's own changes.
5) Fast dashboards for a read-light, write-heavy system#
Reads are few compared with writes, but each one must be fast. The Read API serves dashboards from precomputed data: balances from the accounts table, month-to-date spending from the monthly spending table, recent transactions from the transaction store's per-user index, and all of it through a cache (Redis or Memcached) with cache-aside reads. Static assets (the app's code, merchant logos, category icons) come from a CDN in front of object storage. When a sync changes a user's data, the pipeline invalidates that user's cached dashboard.
6) Analytics over transactions#
Two kinds of analytics exist:
- Per-user analytics (trends, "you spent 20% more on dining than last month", recurring bills) are computed from the user's own transactions and aggregates, in the same pipeline as budgets or by nightly batch jobs per user.
- Product and population analytics (which categories grow, categoriser accuracy, connection success rates by bank) run in a separate data warehouse (BigQuery, Redshift, Snowflake, ClickHouse) fed from the event stream, with personal fields removed or tokenised. Keeping this off the main databases is essential: one large group-by over billions of rows would otherwise slow down every user's sync.
The full high-level design#
Components:
| Component | Responsibility | Technology choices |
|---|---|---|
| API Gateway | Authenticates users, enforces per-user rate limits, routes to services | Envoy, Kong, AWS API Gateway; see API Gateway and Backend-for-Frontend |
| Connection Service | Link sessions, token exchange, connection status, re-authentication, unlinking | Stateless service over the core DB |
| Credential Vault | Stores tokens and any credentials encrypted with envelope encryption; only sync workers and the connection service may decrypt | Dedicated service and database, AWS KMS or Google Cloud KMS, HashiCorp Vault; HSM-backed master keys |
| Sync Scheduler | Creates daily jobs for active connections, spread over time, with priorities | A sharded cron over the connections table, or a workflow engine |
| Sync Queue | Buffers work, separates priorities (on-demand, initial, scheduled), absorbs bursts | SQS, RabbitMQ or Kafka; see Asynchronous Processing and Message Queues |
| Sync Workers | Fetch deltas, store raw payloads, normalise, upsert, advance cursors | Autoscaled worker pool |
| Connector Gateway | One adapter per provider; per-institution and per-provider rate limits; circuit breakers; failover between aggregators | Internal service with token buckets in Redis |
| Transaction Store | Durable, idempotent storage of transactions, sharded by user | Sharded PostgreSQL or MySQL, or Cassandra or DynamoDB with per-user partitions |
| Event Stream | Carries added, changed, removed and categorised events to consumers | Kafka, Kinesis |
| Category Service | Merchant normalisation, user rules, model scoring, crowd feedback | Stateless consumers with an in-memory merchant dictionary |
| Budget Service | Monthly spending aggregates, budget templates and overrides, threshold detection | Stream consumers; aggregates in the core DB or a key-value store |
| Notification Service | Delivers alerts once, honours preferences and quiet hours | See the notification system case study |
| Read API and Cache | Dashboard and list queries from precomputed data | Redis or Memcached, read replicas |
| Object Store | Raw payloads for replay and audit | S3, Google Cloud Storage |
| Data Warehouse and batch | Population analytics, re-aggregation and backfills | BigQuery, Redshift, Snowflake, ClickHouse; Spark |
Key Flows#
Flow 1: Linking an account through bank OAuth#
- The app asks the Connection Service for a link session. The service asks the aggregator for a short-lived link token tied to our user id and the products we need (transactions, balances).
- The aggregator's widget sends the user to the bank's own login page. The user logs in there, passes the bank's multi-factor check, and picks which accounts to share. The bank redirects back with an authorisation code, which the aggregator exchanges for bank tokens that it keeps.
- The widget gives the app a public token: short-lived and useless on its own.
- Our backend exchanges the public token for a long-lived access token in a server-to-server call authenticated with our client id and secret. The access token goes straight into the vault; the core database stores the connection with the vault reference, the provider's item id and status
ACTIVE. - The service fetches the account list immediately, so the user sees "3 accounts linked" within a few seconds, and queues an initial sync in the high-priority lane.
- The initial sync usually returns little at first; the provider gathers history in the background. Plaid's documentation, for example, describes an initial update (recent transactions) followed by a historical update, with a webhook for each, and a
days_requestedsetting from a default of 90 days up to 730 days.
If the bank has no OAuth, step 2 shows the aggregator's own credential form instead; the aggregator stores the username and password in its own vault and logs in on our behalf. Our side of the flow is identical, which is the main reason to use an aggregator.
Flow 2: Daily scheduled sync with a cursor#
- Every night the scheduler selects connections whose owners were active in the last 30 days and gives each a run time spread over the day, with random jitter, so the morning does not start with 6 million jobs at once.
- A worker takes the job, reads the connection's cursor (an opaque marker of the last change we received), and decrypts the token inside the worker's memory only.
- The Connector Gateway checks the rate limits for this provider and this bank. If the bank is over its budget, the job goes back on the queue with a delay instead of failing.
- The provider returns only changes since the cursor: added, modified and removed transactions, a new cursor, and a
has_moreflag for paging. - The worker writes the raw response to object storage, then in one database transaction: upserts added and modified transactions by their source ids, marks removed ones, saves the new cursor, and writes outbox rows for the event stream. If the worker dies before commit, the job is retried from the old cursor and the upserts are idempotent, so nothing is duplicated.
- Only after the commit does the worker acknowledge the job.
Flow 3: On-demand refresh#
- The user pulls to refresh. The app calls
POST /connections/{id}/refreshwith an idempotency key. The Refresh API checks the per-user limit (one forced refresh per connection per 15 minutes) and returns202with a job id. - The app keeps showing cached data, with "Updating…" next to the account.
- The job goes into the on-demand lane, which workers serve before scheduled work. If the provider supports a forced refresh (Plaid offers
/transactions/refreshas an add-on), the worker requests one; the provider then contacts the bank and later sends a "new data available" webhook. If not, the worker pulls the latest deltas directly. - When the webhook arrives, a delta pull runs as in Flow 2. Once the transactions are stored and categorised, a push message tells the app to reload. Typical end-to-end time: 5–30 seconds, depending on the bank.
- If nothing changes within 60 seconds, the app stops spinning and shows "Last updated 6:17 a.m."; it never blocks the user on a bank.
Flow 4: A pending transaction posts#
Asha pays $42.10 for dinner on Friday. On Friday night the card's bank reports a pending transaction of $42.10, "BISTRO 22 PENDING". On Monday, with the tip added, it posts as $50.52, "BISTRO 22 SAN FRANCISCO CA".
- Many providers link the posted record to the pending one (Plaid, for example, includes a
pending_transaction_idon the posted transaction that points at the pending one). - The worker treats the pair as one logical transaction: it keeps our internal transaction id, copies across anything Asha did to the pending version (a note, a changed category), and updates amount, date, description and status.
- The Budget Service receives a single "replaced" event and adjusts the dining total by the difference (+$8.42), so the budget never counts the dinner twice.
- When the provider does not link them, a matching rule pairs them: same account, a posted transaction within a few days of the pending one, similar description and an amount within a tolerance (tips and fuel pre-authorisations change amounts). Deep dive 4 covers this.
Flow 5: The user changes a category and creates a rule#
- Sam sees "AMZN Mktp US" categorised as "Shopping", but it was a book for a course, so they change it to "Education" and tick "apply to similar transactions".
- The Edit API updates the transaction with
category_source = USERandif_version, and creates a rule (merchant "Amazon" plus description text containing "Mktp", then "Education") only if Sam chose a rule; otherwise only this transaction changes. - An event "category changed" goes to the stream. The Budget Service moves the amount from Shopping to Education in the monthly spending table for that month.
- If Sam chose "apply to past", a background job re-categorises their past matching transactions, skipping any that Sam edited by hand, and emits one event per changed transaction so that aggregates follow. It runs in the user's own partition and finishes in seconds.
- The edit is also a signal for the global categoriser: an anonymised "merchant M was moved from Shopping to Education" vote goes to the crowdsourcing pipeline (deep dive 5).
Flow 6: A budget alert fires once#
- Kai's dining budget is $200 for November. A new $38 dining transaction arrives.
- The Budget Service applies it to Kai's November dining total atomically, reading the old total and the new one in the same statement.
- It compares them with the thresholds: the old total ($172) was already over 80% (the 80% alert fired earlier), and the new total ($210) crosses 100%. So one alert is emitted with a deterministic key: (user, month, category, threshold).
- The Notification Service stores the key with a unique constraint before sending. A replayed event or a retry finds the key and does nothing, so Kai gets the message once.
- If a refund later brings the total back under $200, no new message is sent; if spending crosses 100% again, it is still the same key, so Kai is not alerted a second time that month.
Flow 7: A connection breaks and the user fixes it#
- The bank changes its login, a password changes, or an EU consent reaches its expiry. The next sync gets an error such as "login required".
- The worker marks the connection
NEEDS_REAUTH, stops scheduling syncs for it (retrying a dead login only creates noise at the bank and can lock the user's account), and emits a "connection broken" event. - The user sees a banner: "Reconnect Chase to keep your data up to date". The Notification Service may also send one reminder.
- The user taps it and goes through a shorter link flow in update mode: the same connection, new credentials or a new consent. On success the status becomes
ACTIVE, the cursor is kept, and a sync fetches everything missed while it was broken.
Data Model#
The core tables, in PostgreSQL syntax. The transaction table's primary key starts with user_id so that one user's data stays together on one shard and in one index range.
CREATE TABLE connections (
id bigint PRIMARY KEY,
user_id bigint NOT NULL,
institution_id int NOT NULL,
provider text NOT NULL, -- 'aggregator_a', 'open_banking_uk', ...
provider_item_id text NOT NULL,
status text NOT NULL, -- ACTIVE, NEEDS_REAUTH, ERROR, REVOKED
sync_cursor text,
consent_expires_at timestamptz,
last_synced_at timestamptz,
UNIQUE (provider, provider_item_id)
);
CREATE TABLE transactions (
user_id bigint NOT NULL,
id bigint NOT NULL, -- our id, stable across pending -> posted
account_id bigint NOT NULL,
source_id text NOT NULL, -- provider's transaction id
status text NOT NULL, -- PENDING, POSTED, REMOVED
authorized_date date,
posted_date date,
amount_minor bigint NOT NULL, -- cents; positive = money out
currency char(3) NOT NULL,
raw_description text NOT NULL,
merchant_id bigint,
category_id int,
category_source text, -- USER, USER_RULE, MERCHANT, MODEL, PROVIDER
note text,
version int NOT NULL DEFAULT 1,
PRIMARY KEY (user_id, id),
UNIQUE (user_id, account_id, source_id)
);
CREATE INDEX tx_by_date ON transactions (user_id, posted_date DESC, id DESC);The aggregate and budget tables are small and keyed the same way:
CREATE TABLE monthly_spending (
user_id bigint, month date, category_id int,
total_minor bigint NOT NULL, txn_count int NOT NULL,
PRIMARY KEY (user_id, month, category_id)
);
CREATE TABLE budget_overrides (
user_id bigint, category_id int, amount_minor bigint NOT NULL,
PRIMARY KEY (user_id, category_id)
);Notes on the schema:
- Money as integer minor units.
amount_minorstores cents as a 64-bit integer. Floating-point numbers cannot represent most decimal amounts exactly, and summing millions of them drifts. UNIQUE (user_id, account_id, source_id)is the deduplication guard: inserting the same provider transaction twice becomes an update, never a second row.category_sourcerecords who decided the category. The categoriser may change rows whose source isMODEL,PROVIDERorMERCHANT, but never rows whose source isUSERorUSER_RULE.versionsupports optimistic concurrency between user edits and sync updates.- No credential columns. The primer-style schema of an
accountstable withaccount_loginandaccount_password_hashis a trap: a hash cannot be reversed, so the service could never log in to the bank with it. The secret must be either an OAuth token or an encrypted credential, and it belongs in a separate vault with its own keys and access control (deep dive 2). - Budgets store only changes. A user's effective budget is the template for their income tier with
budget_overridesapplied on top.
Which store holds what.
| Data | Store | Why |
|---|---|---|
| Users, connections, accounts, budgets, rules | PostgreSQL (or MySQL), sharded by user when needed | Relational, small, transactional updates |
| Transactions | Sharded PostgreSQL by user_id, or Cassandra or DynamoDB with partition key user_id (or user_id plus month) | Very high write volume, per-user range reads, idempotent upserts |
| Monthly spending | Same shard as the user's transactions, or a key-value store | Updated with each categorised transaction; read on every dashboard |
| Credentials and tokens | Separate vault database plus KMS | Different blast radius, different access rules |
| Raw payloads | Object storage (S3, GCS) with lifecycle rules | Cheap, immutable, replayable |
| Merchant dictionary | PostgreSQL plus in-memory copy in each categoriser | Read-mostly, small hot set |
| Dashboards and sessions | Redis or Memcached | Cache-aside for hot reads |
| Population analytics | Data warehouse (BigQuery, Redshift, Snowflake, ClickHouse) | Columnar scans over billions of rows |
| Search over a user's transactions | Database indexes per user, or Elasticsearch for full text | Most users have a few thousand transactions, so per-user indexes usually suffice |
For a structured way to make these choices, see Choosing a Database: A Decision Guide.
Deep Dives#
1. Three ways to get the data: open-banking APIs, aggregators and screen scraping#
Every feature in this product depends on reading data from banks we do not control. There are three ways to do it, and a real product uses all three for different institutions.
a) Screen scraping (credential-based access). The user types their online-banking username and password into the app (or into an aggregator's form). A server then logs in to the bank's website as that user, usually with a headless browser, or calls the private API behind the bank's own mobile app, and reads balances and transactions from the responses.
- Why it existed. Until open-banking rules arrived, most banks offered no third-party API at all. Scraping was the only way to connect to thousands of institutions. Yodlee, founded in 1999 per its Wikipedia article, built its business on exactly this: a single website where users entered access details for their other accounts.
- How it works in practice. A connector per bank knows the login sequence, the pages or private endpoints to call and how to parse them. It must answer security questions and one-time codes: the first login usually triggers an SMS code, which the user types into the aggregator's form, and the aggregator then stores a device cookie so that later logins look like the same trusted device.
- Why it is fragile. Each connector breaks when the bank redesigns its site, adds a new multi-factor step, or deploys bot detection. With thousands of banks, some connectors are always broken. An aggregator therefore runs connector health monitoring and teams that fix connectors every day.
- Why it is risky. The service holds the user's real password, which usually grants full access, including moving money, not just reading. If the password store leaks, attackers can log in as the user. Mint's Wikipedia article records a 2010 controversy over exactly this: Mint asked for usernames and passwords and stored them in a decryptable form, raising the fear that a breach would expose them. Banks also dislike scraping because it looks like a bot attack, adds load to their login systems, and leaves them unsure who to blame for fraud.
b) Aggregators. Instead of building thousands of connectors, the app uses one or a few aggregators (Plaid, Yodlee, MX, Finicity and others). The aggregator offers one API: link an account, list accounts, sync transactions, get balances. Under the hood it uses whatever works for each institution: an official API where one exists, a bilateral agreement, or scraping.
- Plaid's Wikipedia article describes the origin story well: its founders first tried to build budgeting and bookkeeping products, struggled to connect bank accounts, and switched to building a unified banking API. The article also notes that for some banks users share their credentials with Plaid, while for others they authorise access through the bank's own portal.
- Advantages. Coverage, one integration, a common data format, enrichment (merchant names, logos, categories) and webhook-based updates.
- Costs. Per-account and per-call fees, dependence on a third party's uptime, and a privacy chain: users' data passes through another company. Aggregators have faced legal challenges over this. Plaid's article notes that TD Bank sued it in 2020, and that in 2021 Plaid settled a $58 million class action over claims that it collected and shared banking data without proper consent. Yodlee's article describes a 2020 class action alleging that it sold consumers' data without adequate consent. For a product, this means the aggregator's practices become your reputational risk, and your consent screens must be clear.
c) Official open-banking APIs (token-based access). The bank exposes a documented API. The user logs in on the bank's own page, approves the specific data to share and for how long, and the third party receives an OAuth access token limited to that scope. Our servers, and even the aggregator's servers, never see the password.
- Regulation drives this. Wikipedia's open banking article explains that the EU's revised Payment Services Directive (PSD2), adopted in 2015, created regulated "account information services". In the UK, the Competition and Markets Authority ordered the nine largest banks in 2016 to give licensed providers access to transaction data, effective 13 January 2018, using standards from Open Banking Limited. Australia launched its Consumer Data Right for banking on 1 July 2019. In the US, the Consumer Financial Protection Bureau finalised a Personal Financial Data Rights rule under Section 1033; the CFPB's announcement says it requires providers to make transaction, balance and other data available to authorised third parties free of charge, and that it aims to move the industry away from screen scraping. Its compliance dates were phased by institution size, from 1 April 2026 for the largest to 1 April 2030 for the smallest, though the agency's page is now marked as archived, so a designer should check the rule's current status.
- Bilateral agreements came first in the US. Mint's article notes that in January 2017 Intuit and JPMorgan Chase agreed that Chase customers' data would flow to Mint without Intuit storing names and passwords. Envestnet's article notes a similar December 2019 agreement between Envestnet (Yodlee's owner at the time) and Chase to protect customers' data through an API.
- Downsides. Each country has its own standard (the EU alone has several API standards, such as the Berlin Group's NextGenPSD2 and France's STET), banks implement them with different quality, consents expire, and the redirect journey loses users. Wikipedia's open banking article reports that in Brazil, the world's largest open-finance system with more than 100 million connected accounts by 2026, fewer than half of users complete the consent journey, according to the Brazilian Association of Fintechs.
Comparison.
| Screen scraping | Aggregator | Official open-banking API | |
|---|---|---|---|
| Coverage | Almost any bank with a website | Thousands of banks, mixed methods | Only banks that offer it (growing, mandated in some countries) |
| What we hold | The user's real password | An aggregator token | A scoped OAuth token |
| Reliability | Breaks on site changes and MFA | Depends on the aggregator's connectors | Best, but varies by bank |
| Data quality | Whatever the page shows | Normalised and enriched | Structured, standard fields |
| Cost | Our own engineering | Per account or per call | Usually free by regulation (in some countries) |
| Legal standing | Grey area, under pressure | Contracts plus consent | Explicitly regulated |
The design choice. Our system speaks to a provider abstraction. Each institution has a routing entry: "use the direct UK open-banking API", "use aggregator A", "aggregator B as fallback". The Connector Gateway exposes one internal interface (link, accounts, syncSince(cursor), balances, revoke) and hides the differences. We do not build our own scrapers: the security and legal risk is better carried by a specialist, and the market is moving to tokens.
Choosing a provider per institution. For each bank we track, per provider, the link success rate, the sync success rate, data freshness and cost. New links go to the best provider for that bank. Existing connections usually stay where they are, because tokens are not portable between providers: moving a user from aggregator A to B normally requires them to log in again. That is why provider choice at link time matters and why the routing table is data, not code.
The connection life cycle.
The important distinction is between transient errors (bank timeout, provider 5xx, rate limit), which deserve automatic retry with back-off, and user-action errors (wrong password, new MFA, consent expired), which must never be retried automatically. Retrying a bad password can lock the user out of their own bank account, and the bank sees it as an attack.
Consent expiry. Under the original PSD2 technical standards, an account-information provider could read data without a fresh strong customer authentication for up to 90 days; after that, the user had to authenticate with the bank again. Wikipedia's PSD2 article notes that in 2021 the European Banking Authority consulted on changing this, and the UK's Financial Conduct Authority (policy statement PS21/19) proposed replacing the 90-day re-authentication with the user reconfirming consent directly with the provider. The US CFPB rule, per its announcement, limits access to one year without reauthorisation. The design implication is the same everywhere: store consent_expires_at per connection, remind the user a week before expiry, and make re-consent a two-tap flow.
2. Secure credential and token storage#
This is the deep dive interviewers care most about, because the naive answer is wrong in an instructive way.
Why a password hash is wrong here. For our own login we store a slow, salted hash of the user's password (bcrypt, scrypt or Argon2) because we only need to check a password, never to recover it. But an aggregator that logs in to a bank must present the secret to the bank. A hash is one-way, so a hash of the bank password is useless. The secret must be stored in a recoverable form: encrypted, not hashed. And the best secret is one that is not a password at all: an OAuth or aggregator token, scoped to read-only access and revocable without changing the user's bank password. See Security Fundamentals for System Design.
What we actually store.
| Connection type | Secret we hold | Power if stolen |
|---|---|---|
| Aggregator connection | Aggregator access token (useless without our client secret) | Read data through the aggregator, only from our account |
| Direct open-banking connection | OAuth access token (minutes to hours) plus refresh token (days to months) | Read the scoped data until expiry or revocation |
| Legacy credential connection (avoid) | Username, password, device cookie, security answers | Full online-banking access |
Even the "weakest" of these is a high-value secret, because millions of them together give access to the finances of millions of people.
Envelope encryption. Wikipedia's article on hybrid cryptosystems describes envelope encryption as the pattern used by all major cloud providers: generate a data encryption key (DEK) locally, encrypt the data with it, then ask a more secure service to wrap (encrypt) the DEK with a key encryption key (KEK) that never leaves that service. Store the wrapped DEK next to the ciphertext. To decrypt, send the wrapped DEK to the key service to unwrap it, then decrypt locally. The KEKs can live in hardware security modules.
Practical details that make it strong:
- One DEK per connection (or per user). A leaked DEK exposes one connection, not all of them. Encrypt with an authenticated mode such as AES-256-GCM, and bind the ciphertext to the connection id as associated data, so an attacker who can write to the database cannot swap one user's ciphertext into another user's row.
- KMS access is the real perimeter. A stolen copy of the vault database, or a backup, is useless without unwrap permission on the KEK. Only the sync-worker role and the connection-service role may call unwrap, and only from production networks. Every unwrap is logged with the connection id, so an unusual pattern (one machine unwrapping 100,000 tokens an hour) raises an alert.
- Keep plaintext short-lived. Unwrapped DEKs and tokens live only in worker memory, for the duration of one sync, and never in logs, traces, crash dumps or error messages. A log scrubber that rejects token-shaped strings is cheap insurance.
- Separate the vault. The vault is its own service with its own database, network rules and on-call. The main application database holds only an opaque reference. A SQL injection bug in the Read API cannot reach tokens.
- Rotation. Rotating the KEK is cheap with envelope encryption: re-wrap each DEK under the new KEK (a few bytes each) without re-encrypting the data. Rotating DEKs means re-encrypting each record, done lazily on the next write. Most KMS products support automatic KEK rotation while keeping old versions for decryption.
- Crypto-shredding. To delete a connection's secret everywhere, including backups, delete its DEK. The ciphertext in old backups becomes unreadable. This is how we honour "delete my data" across systems that keep immutable copies.
- Revocation first. On unlink, call the provider's revoke endpoint before deleting locally, so the token is dead even if a copy exists somewhere.
The rest of the data. Transactions are less dangerous than tokens but still personal and sensitive. They are encrypted at rest (disk or database-level encryption with KMS keys), sent only over TLS, and accessed by staff only through audited, just-in-time tools. Account numbers are stored masked ("•••• 1234"); full numbers, where a product needs them, go into the vault too.
Threats and answers.
| Threat | Answer |
|---|---|
| Database dump or stolen backup | Ciphertext only; KEKs never leave the KMS |
| Compromised application server | It holds no unwrap permission unless it is a sync worker; workers are isolated and monitored |
| Compromised sync worker | Rate limits and anomaly detection on unwraps; short-lived worker credentials; tokens are read-only scopes |
| Malicious insider | Two-person rule for KMS policy changes, access logs reviewed, no human unwrap path |
| Phishing users with fake "link your bank" pages | Use the bank's own OAuth page wherever possible, so users learn to log in only on their bank's domain |
| Token replay from another client | Aggregator tokens are bound to our client id and secret; OAuth tokens to our client registration, ideally with mutual TLS |
3. Scheduling syncs: who, when and how often#
Sync is where the money goes: provider fees, bank load and worker capacity. A good scheduler decides who to sync, when, and in what order.
Who. The primer-style rule is the right starting point: automatic daily updates only for users active in the last 30 days. Refine it:
- Users who opened the app today, or have a budget near its limit, get an extra midday sync.
- Users inactive for 30–90 days get a weekly sync (so that their first screen on return is not empty), and users inactive for longer get none until they log in.
- Connections in
NEEDS_REAUTHget none. - Accounts that rarely change (a mortgage, a car loan) sync balances weekly.
With these rules, the 15 million connections need about 6–7 million automatic syncs a day instead of 15 million.
When. Banks post most transactions overnight, so a sync at 6 a.m. local time catches the night's postings. But scheduling all 6 million at 6 a.m. would create a thundering herd. The scheduler instead:
- Assigns each connection a stable slot in a morning window, derived from a hash of the connection id (so the slot is the same every day and the load is even), plus small random jitter.
- Spreads slots by time zone, which naturally flattens the global load.
- Applies per-institution budgets: if a bank allows 50 concurrent sessions for our client, the slots for that bank's 400,000 connections are spread so that no more than 50 run at once.
Webhooks instead of polling where possible. If the aggregator already polls banks and tells us when something changed, our own daily poll is mostly wasted. With webhooks, the daily scheduled sync becomes a safety net (catch missed webhooks) and can run less often, while most work is driven by "new data available" events. The Plaid documentation, for example, tells integrators to call its sync endpoint when it fires SYNC_UPDATES_AVAILABLE, and describes update checks one to four times a day depending on the institution.
Priority lanes. One queue with one priority would let a morning batch of scheduled syncs delay a user who is staring at a spinner. So the Sync Queue has lanes:
| Lane | Examples | Target latency to start |
|---|---|---|
| Interactive | User pressed refresh, just linked an account | Under 1 second |
| Event-driven | Provider webhook "new data available" | Under 1 minute |
| Scheduled | Daily sync of active users | Within its time window |
| Backfill | Historical pulls, re-processing raw data | Best effort |
Workers take from the interactive lane first, but weighted fair scheduling (for example 50% interactive, 30% event, 15% scheduled, 5% backfill when all are full) keeps lower lanes from starving.
Rate limiting at the Connector Gateway. Each provider and each institution has a token bucket, kept in Redis and shared by all workers: for example aggregator A at 2,000 requests per second for our account, and Bank X at 50 concurrent sessions. A worker that cannot get a token re-queues the job with a delay rather than spinning. A circuit breaker per institution opens when error rates rise (the bank is down), so jobs for that bank are delayed in bulk instead of each one failing slowly (see Rate Limiting and Throttling and Resilience Patterns: Timeouts, Retries and Circuit Breakers).
Back pressure. If the Transaction Store or the categoriser falls behind, workers slow down. They check the event stream's consumer lag and the database's write latency, and when either exceeds a threshold, the scheduled and backfill lanes pause while the interactive lane continues. This is the difference between a slow morning and an outage.
Sizing the worker pool. Using the capacity numbers: about 400 jobs per second in the busiest window, about 3 seconds each, so about 1,200 jobs in flight. Workers are I/O-bound (waiting on providers), so an asynchronous worker can hold 100–200 jobs at once; 10–20 worker instances suffice, with autoscaling on queue depth. The real limit is the providers' concurrency, not our CPU.
4. Incremental sync, deduplication and the pending-to-posted problem#
Fetching transactions is easy. Fetching them again and again, from unreliable sources, without ever showing a duplicate or losing one is the real problem.
Why duplicates happen.
- Retries. A worker crashes after storing half a page, or the provider times out after sending the data, and the job runs again.
- Overlapping windows. Date-based pulls ("give me the last 7 days") overlap by design, so every pull returns many transactions we already have.
- Pending to posted. The same purchase appears twice with different ids, amounts and descriptions.
- Re-linking. A user unlinks and re-links the same bank, or links it again through a different provider, and the history comes back with new ids.
- Provider changes. The provider re-ids transactions after an internal migration (rare, but it happens).
Cursor-based deltas beat date windows. A modern sync API returns an opaque cursor that marks the last change we have seen. Each call returns added, modified and removed lists since that cursor, plus a new cursor. Plaid's /transactions/sync works this way: the first call has no cursor and returns the full history, later calls return only changes, results are paged (count defaults to 100 and allows up to 500 per page), and has_more says whether to keep paging. Its documentation adds a subtle rule: if the data changes in the middle of paging (it raises a TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION error), the client must restart from the cursor it had before paging began. So the worker must keep the old cursor until the whole page set is stored, and only then save the new one.
The general rule: store the data and the new cursor in the same database transaction. If they are written separately, a crash between the two either skips data (cursor saved, data not) or reprocesses it (data saved, cursor not). The second is harmless only if writes are idempotent.
function syncConnection(conn):
startCursor = conn.cursor
cursor = startCursor
added, modified, removed = [], [], []
loop:
page = provider.sync(conn.token, cursor, count = 500)
if page.error == MUTATION_DURING_PAGINATION:
cursor = startCursor; added, modified, removed = [], [], []; continue
added += page.added; modified += page.modified; removed += page.removed
cursor = page.next_cursor
if not page.has_more: break
rawStore.put(conn.id, now(), all pages) # replayable
db.transaction:
for t in added + modified: upsertBySourceId(conn.user_id, t) # idempotent
for r in removed: markRemoved(conn.user_id, r.source_id)
linkPendingToPosted(conn.user_id, added)
conn.cursor = cursor # same commit
outbox.append(events for every change)Idempotent upserts. The unique key is (user_id, account_id, source_id). In PostgreSQL:
INSERT INTO transactions (user_id, id, account_id, source_id, status, posted_date,
amount_minor, currency, raw_description, version)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 1)
ON CONFLICT (user_id, account_id, source_id) DO UPDATE
SET status = EXCLUDED.status,
posted_date = EXCLUDED.posted_date,
amount_minor = EXCLUDED.amount_minor,
raw_description = EXCLUDED.raw_description,
version = transactions.version + 1
WHERE (transactions.status, transactions.amount_minor, transactions.raw_description)
IS DISTINCT FROM (EXCLUDED.status, EXCLUDED.amount_minor, EXCLUDED.raw_description);The WHERE clause turns a replay of unchanged data into a no-op: no version bump, no event, no wasted work downstream. User-owned fields (category set by the user, notes) are deliberately not in the SET list, so a sync can never overwrite them.
Linking pending to posted. When the provider gives a link (a posted transaction carrying the pending transaction's id), we:
- find our row for the pending source id,
- update that same row in place with the posted data (keeping our internal
id, the user's notes and any user category), - record the posted source id so future updates match,
- emit one "replaced" event carrying the old and the new amount.
When no link is given, a matcher runs over the user's recent pending transactions:
| Signal | Typical rule |
|---|---|
| Same account | Required |
| Dates | Posted within 0–7 days of the pending date (hotels and car rentals can take longer) |
| Amount | Equal, or within a tolerance: up to about 20–25% higher for restaurants (tips); any amount for fuel pre-authorisations, which are often a fixed hold that settles to the real amount |
| Description | High similarity after normalisation (same merchant id, or a token-overlap score above a threshold) |
| Uniqueness | Only one candidate; if two pending coffees match one posted coffee, pick the closest amount and date, and never match the same pending twice |
Unmatched pending transactions are removed automatically after a timeout (for example 14 days), because some authorisations simply expire without posting. The dashboard should show pending transactions in a separate style and, ideally, count them in budgets (people want to know they just spent $80) while making clear they may change.
Duplicate accounts across connections. If a user links the same bank twice (through two providers, or by mistake), each account appears twice. Detect it by institution plus account mask plus account type plus similar balance, and ask the user to merge, rather than guessing. Merging keeps the older connection's history and drops the newer connection's copies.
Removed and corrected transactions. Banks reverse duplicates they posted, change descriptions and occasionally change amounts. A removed event marks the row REMOVED (kept for a short time for audit and so that late events referring to it can be recognised), and the aggregates subtract it. Corrections flow as modified with new values.
Where the uniqueness check runs: one partition per user. Deduplication needs an atomic "insert if not exists" on the transaction's key. In a single PostgreSQL shard that is the unique index above. In a wide-column store such as Cassandra, the equivalent is a lightweight transaction (INSERT … IF NOT EXISTS), which uses a Paxos round to give a linearizable check, but only within one partition, and it costs several extra network round trips compared with a normal write. The same lesson that applies to swipe matching in a dating app applies here: put every record that must be checked together in the same partition. With partition key user_id (or user_id plus month for very active users), every dedupe check, every pending-to-posted match and every aggregate update for one user stays inside one partition, so no cross-partition coordination is ever needed. The cost is that we must watch partition sizes (a power user or a small business with 50,000 transactions a month makes a big partition) and archive old months.
A cheaper alternative in Cassandra is to make the write itself idempotent and skip the conditional check: use the provider's source_id as part of the clustering key, so a replay simply overwrites the same cell with the same data. Conditional writes are then needed only for the rarer operations that truly read-then-write, such as linking a pending transaction to its posted version.
5. Categorisation: merchants, rules, models and the crowd#
A category is only useful if it is right most of the time and never fights the user. The categoriser is a pipeline of steps, from the most specific to the most general, and the first confident answer wins.
Step 1: clean the description. Bank descriptions are messy: "POS DEBIT 1123 SQ JOES CAFE SEATTLE WA 98101", "AMZN Mktp US2K4L77", "PAYPAL *SPOTIFY 4029357733". Normalisation removes noise (card-network prefixes, store numbers, dates, reference numbers, city and state), recognises payment intermediaries ("SQ *" for Square, "PAYPAL ", "TST" for Toast) and extracts the underlying merchant text ("JOES CAFE", "SPOTIFY"). This is mostly rules and regular expressions, maintained as data.
Step 2: map to a merchant. The cleaned text is looked up in the merchant dictionary: known merchants with their aliases, default category and logo. The dictionary starts with the most popular sellers (the primer sizes a starter set of 50,000 sellers at about 255 bytes each, roughly 12 MB), and grows as the crowd and the data team add more. Lookups that miss go to fuzzy matching (token overlap, edit distance, location), and still-unknown merchants become "candidate merchants" for review.
Step 3: apply user rules. If the user has a rule for this merchant or text, apply it. Rules beat everything except a manual change on this very transaction.
Step 4: merchant default, provider category or model.
- The merchant's default category is right for most single-purpose merchants (a coffee chain, a fuel brand).
- The provider's category may be available with a confidence. Plaid's API, for example, returns a
personal_finance_categorywith a primary and a detailed category and a confidence level, whereVERY_HIGHmeans "more than 98% confident" andHIGH"more than 90%". Its documentation reports typical fill rates of 97% for merchant name and 95% for category, excluding transactions with no merchant (cash, direct deposits, bank fees). - The MCC helps for card transactions: 5411 is grocery stores, 5541 service stations.
- A model handles the rest: features from the cleaned description (character n-grams), amount, MCC, day of week, account type, whether the amount repeats monthly, and the user's history. A gradient-boosted tree or a small text classifier is enough; it outputs a probability per category.
Step 5: decide and record why. Store the category with category_source (USER, USER_RULE, MERCHANT, PROVIDER, MODEL) and a confidence. Low-confidence results can be shown with a gentle "Is this right?" prompt, which also gathers labels.
Multi-purpose merchants are the hard case. A big-box store or an online marketplace sells food, clothes and electronics, so its merchant default is a guess. Good answers: a broad "Shopping" default, user rules, and, where available, line-item data from receipts or the merchant. The model can also learn per-user patterns ("this user's Amazon purchases are usually books").
Never auto-recategorise a user's choice. The primer makes this an explicit requirement, and it is the single most important rule for trust. When a better model ships, it may re-score MODEL and MERCHANT transactions, but never USER or USER_RULE ones. A batch re-categorisation emits "category changed" events, so aggregates follow.
Crowdsourcing: learning from users' corrections. Each manual change is a vote: "merchant M should be category C". Aggregated across millions of users, these votes fix the dictionary:
- Keep, per merchant, a count per suggested category. The primer suggests a heap per seller to get the most-voted override quickly; since categories are few (dozens), a simple map of counts with the top entry tracked is just as good.
- Change the merchant's default only when the top override has enough votes (for example at least 50 distinct users) and a clear majority (for example 70% of all corrections for that merchant), and the change is reviewed or tested on held-out data first. A few users can be wrong, and some may try to game it.
- For millions of long-tail merchants, a streaming top-k structure (count-min sketch plus a small heap) keeps the memory small; see Probabilistic Data Structures for Big Data.
- Corrections are also training labels for the model, with care: people correct mistakes far more often than they confirm correct guesses, so labels are biased toward hard cases.
Measuring quality. Track the correction rate (the share of categorised transactions that users change) per category, per merchant and per model version. A spike after a release is the clearest signal of a regression. Hold out a labelled sample for offline evaluation (precision and recall per category), and run new models in shadow mode first.
Transfers are not spending. A payment from checking to a credit card, or a move from checking to savings, shows up as two transactions (money out of one account, money into another). Counting both as spending inflates budgets. Detect transfer pairs (same user, opposite amounts, within a few days, descriptions like "PAYMENT THANK YOU" or "TRANSFER TO SAV") and categorise them as "Transfer", excluded from spending. Similarly, refunds should reduce the original category's spending, not count as income.
6. Budgets and alerts#
Suggesting a budget. A new user has no budget, and a blank form is discouraging. The service estimates monthly income from regular deposits (payroll-like credits arriving every two weeks or monthly) and then proposes a budget from a template for that income tier, such as:
| Category | Share of income |
|---|---|
| Housing | 40% |
| Food | 20% |
| Transport (fuel, transit) | 10% |
| Shopping | 20% |
| Everything else | 10% |
A better suggestion also looks at the user's actual average spending over the last three months per category, and suggests something between the template and reality, so the target is achievable.
Storing only changes. With 10 million users and about 10 categories each, a full budget table has 100 million rows, almost all identical to the template. Storing only budget_overrides (the rows the user changed) cuts this to perhaps 20–30 million rows and makes template improvements apply automatically to everyone who never changed a value. The effective budget is computed when read: override if present, else template[income_tier][category] × income.
Keeping spending totals current. There are two ways to compute "how much did Kai spend on dining in November":
- Query on demand:
SELECT SUM(amount) FROM transactions WHERE user_id = ? AND month = ? AND category = ?. Fine for one user with a few hundred transactions a month, with a good index. But the dashboard needs every category, every view needs it again, and the alert check needs it after every transaction. - Maintain an aggregate: the
monthly_spendingtable, updated by the Budget Service from events. Each event carries what changed (added amount, removed amount, old and new category for a recategorisation), and the service applies the difference.
The second is what we use for reads and alerts, with the first as the source of truth for repair: a nightly job recomputes each recently changed user-month from the transactions and fixes any drift (see deep dive 8).
Applying deltas safely. Event-driven aggregates break in two classic ways: an event is applied twice (after a retry) or an event is lost. Defences:
- Each event has a unique id. The Budget Service records
(event_id)in a small dedupe table in the same transaction as the aggregate update, so a redelivered event is ignored. Because events for one user are partitioned byuser_id, they arrive in order on one consumer, and the aggregate rows for that user live on the same shard as the dedupe table. - Events carry absolute facts (transaction X now has amount A in category C, version v) rather than only "+38". The service keeps, per transaction, the last version applied, so it can compute the correct difference even if it missed an intermediate event, and can ignore stale events with a lower version.
-- apply a categorised transaction to the monthly total and return before/after
WITH upd AS (
INSERT INTO monthly_spending (user_id, month, category_id, total_minor, txn_count)
VALUES ($1, $2, $3, $4, 1)
ON CONFLICT (user_id, month, category_id) DO UPDATE
SET total_minor = monthly_spending.total_minor + EXCLUDED.total_minor,
txn_count = monthly_spending.txn_count + 1
RETURNING total_minor
)
SELECT total_minor - $4 AS old_total, total_minor AS new_total FROM upd;Detecting threshold crossings. With the old and the new total from the same atomic statement, the check is simple: for each threshold t in the user's settings (for example 80% and 100%), fire if old < t × budget <= new. Because the comparison uses before and after values from one atomic update, two transactions processed concurrently cannot both think they crossed the line (they are serialised on the row), and none can slip past unnoticed.
Firing exactly once. The alert's identity is deterministic: (user_id, month, category_id, threshold). The Notification Service inserts this key with a unique constraint before sending, so retries and replays are harmless (see Idempotency and Safe Retries). The same key also implements the product rule "at most one 100% alert per category per month", even if a refund dips the total below and a new purchase crosses again.
Timing and batching. The requirements say alerts need not be instant. Two options:
- Stream evaluation (the design above): alerts within seconds of the transaction being categorised. Simple and cheap at our scale.
- Batch evaluation: an hourly or daily job compares totals with budgets for users with changes. Cheaper if events are bursty, and lets us combine several alerts into one digest ("You are over budget in 2 categories").
A good product does both: immediate for "over budget" and "large transaction", a daily digest for "approaching budget" and weekly summaries. Respect quiet hours and the user's channel preferences; the notification system case study covers delivery.
Pending transactions and alerts. Counting pending transactions gives earlier warnings but risks false alarms when a pending amount changes or disappears. A reasonable policy: include pending amounts in the displayed total, but fire the 100% alert only on posted amounts, or on pending amounts above a size threshold.
Other alert types follow the same pattern (a deterministic key, an atomic check, a notification queue):
| Alert | Trigger | Key |
|---|---|---|
| Large transaction | A single transaction above the user's threshold | (user, transaction id) |
| Low balance | Available balance falls below a threshold | (user, account, day) |
| Unusual spending | A category's month-to-date spending is far above the user's typical pace | (user, month, category, "unusual") |
| Bill due | A recurring bill is expected in 3 days | (user, recurring stream, due date) |
| Connection broken | Status became NEEDS_REAUTH | (connection, broken-since date) |
| Possible duplicate charge | Two identical charges at one merchant within minutes | (user, pair of transaction ids) |
Rollover and month boundaries. "Month" means the user's local month, so the Budget Service needs the user's time zone; a purchase at 11:30 p.m. on 31 October in California is October spending even though it is 1 November in UTC. Use the transaction's local date from the bank, not the time we received it. Some users want unspent budget to roll over; store a rollover flag per override and compute the carried amount at the month boundary in a scheduled job.
7. Read-heavy dashboards on a write-heavy system#
Overall the system is write-heavy, but each user session is read-heavy: one app open triggers a dashboard, a few lists and charts, and the user expects them in a fraction of a second. The way to serve fast reads on top of a firehose of writes is to precompute what the screens show and cache it, so that reads never scan raw transactions.
What the main dashboard needs.
| Widget | Source | Cost if computed live |
|---|---|---|
| Net worth and balances | Accounts table (a handful of rows) | Cheap |
| This month's spending by category | monthly_spending for (user, month) | Cheap (about 10 rows) |
| Budget progress | Budgets plus monthly_spending | Cheap |
| Recent transactions | Index (user_id, posted_date DESC), top 20 | Cheap with the index |
| 12-month trend | monthly_spending for 12 months | About 120 rows; cheap |
| Insights ("dining up 20%") | Precomputed nightly per user | Expensive live, so precomputed |
| Stale connection banners | Connections table | Cheap |
Because every widget reads a precomputed table or a narrow index range, the whole dashboard can be assembled from 5–7 small queries on the user's own shard, typically 5–20 ms in total.
Caching. Even cheap queries add up at 1,000 requests per second, and many users open the app several times a day while their data changes once or twice. So the Read API uses cache-aside:
function getDashboard(userId):
key = "dash:v3:" + userId
cached = redis.get(key)
if cached: return cached
data = buildDashboard(userId) # 5-7 small queries on the user's shard
redis.set(key, data, ttl = 6 hours)
return data
on event (transaction changed | balance changed | budget changed) for userId:
redis.delete("dash:v3:" + userId) # next read rebuilds- Invalidate on change, not on a timer only. Every event that changes what the dashboard shows deletes the user's key. The TTL is just a safety net.
- Coalesce invalidations. A sync may change 30 transactions in one batch; delete the key once per batch, not 30 times.
- Version the key (
v3). Deploying a new dashboard format just changes the prefix; old entries expire on their own. - Avoid a stampede. After a mass sync (morning), many users' keys are invalidated at once, and their first open rebuilds from the database. That is fine because rebuilds are cheap and spread over the morning; for the rare very hot key, a single-flight lock prevents parallel rebuilds (see Cache Failure Modes: Stampedes, Hot Keys and Penetration).
The primer also lists what is worth caching more broadly: user sessions, aggregate statistics per category, and recent transactions. Strategies other than cache-aside also fit some data: write-through for small, hot objects that we update ourselves (budgets), or refresh-ahead (rebuild the dashboard right after a sync, before the user opens the app) for the most active users. See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
Read replicas. Transaction lists and searches can read from replicas of each shard. The catch is replication lag: a user who just changed a category and immediately reloads might see the old one. Two fixes: read your own writes from the primary for a few seconds after an edit (the client sends a "last write" timestamp), or update the cached copy in place on edit. See Database Replication.
Freshness is part of the read. Every response includes last_synced_at per connection. A dashboard served from cache while a bank is down is still correct as of a time, and saying so ("Updated 2 hours ago") prevents support tickets. This is how the system meets its availability target without depending on banks: reads never call banks.
Static content. The app shell, merchant logos and category icons come from a CDN in front of object storage, so the API serves only small JSON (see Content Delivery Networks (CDN)).
Transaction search. "Find all Uber rides in 2025" is a per-user query: filter by user, date range and merchant id using the composite index; for free-text search over descriptions and notes, a trigram index (pg_trgm) on the user's shard is often enough because each user has only thousands of rows. A separate search cluster such as Elasticsearch, with documents routed by user_id, is worth it only if search features grow (see Elasticsearch and Search Systems).
8. Analytics over transactions: SQL, MapReduce, streams and the warehouse#
There are two very different analytics workloads, and mixing them is a classic mistake.
Per-user analytics answer questions for one person: monthly spending per category, trends, insights, recurring bills, income estimates. They are computed from that user's data and must be correct.
Population analytics answer questions about everyone: which categories are growing, how accurate the categoriser is, which banks fail most, how many users stay within budget. They scan billions of rows and are run by analysts and data scientists.
Computing monthly spending: three ways.
- SQL over the transaction store. A
GROUP BY user_id, month, categoryover one user's rows is fast. Over all users it is a full scan of tens of terabytes, so it must never run on the production databases. - MapReduce over raw logs. The raw transaction logs in object storage (tab-separated lines of
user_id,timestamp,seller,amount) can be aggregated by a batch job. The mapper looks up the seller's category and emits((user_id, month, category), amount); the reducer sums the amounts for each key; the output is loaded intomonthly_spending.
map(line):
user_id, timestamp, seller, amount = line.split("\t")
month = to_local_month(timestamp, user_tz(user_id))
category = category_for(user_id, seller) # user rules, then merchant dictionary
emit((user_id, month, category), amount)
reduce(key, amounts):
emit(key, sum(amounts))In practice this runs on Spark rather than classic Hadoop MapReduce, partitioned by user so each user's rows meet on one machine, and the job is written to be re-runnable: it overwrites the output for the users and months it processed. With 1.8 billion transactions a month at about 300 bytes each in compressed columnar files, a month is about 540 GB, which a modest Spark cluster processes in well under an hour.
3. Streaming aggregation. The Budget Service already maintains monthly_spending from events in near real time (deep dive 6). This is what the dashboard reads.
Why keep the batch path if streaming exists? For the same reason ad-click counting keeps one: the stream path is fast but can drift (a bug, a lost event, a bad deploy, out-of-order events), and the batch path recomputes the truth from immutable raw data. Run the batch job nightly for user-months that changed, compare with the streaming totals, alert on differences, and overwrite with the batch result. This pairing of a fast speed layer with a correcting batch layer is the Lambda architecture (see Batch vs Stream Processing). A simpler variant, often called Kappa, replays the event stream through the same streaming code to recompute; it needs the stream to retain history (or to be re-fed from the raw store).
Recomputation after a category change. The primer notes that when a user changes a category, the analysis must be re-run. With aggregates maintained by events, "re-running" is just applying the difference: move the amount from the old category to the new one for that month. For a rule applied to the past, the job emits one change event per affected transaction, and the totals follow. For a global change (a new model re-categorises many transactions), the batch path is simpler: recompute affected user-months from scratch.
Why not compute everything in the warehouse? The warehouse is excellent for population questions, but it is usually minutes to hours behind, has per-query costs, and is not built for millions of tiny per-user queries at low latency. Per-user aggregates belong in the serving stores; the warehouse gets a copy.
Feeding the warehouse. Events from the stream are written continuously to object storage in a columnar format (Parquet), partitioned by date, and loaded into the warehouse (BigQuery, Redshift, Snowflake, ClickHouse). Before data leaves the production zone:
- Replace
user_idwith a pseudonymous id (a keyed hash) so analysts cannot join it back to names without the key. - Drop free text (notes, raw descriptions) unless a specific analysis needs it and is approved.
- Keep only coarse location (city, not address).
- Enforce access control and logging on the warehouse, and keep retention short for detailed rows.
Columnar storage is what makes population queries cheap. A query such as "average monthly grocery spending by income tier and state in 2025" reads only four columns out of thirty, compresses them heavily, and scans billions of rows in seconds (see Data Pipelines, Warehouses and Lakes).
Typical population analytics for this product:
| Question | Data | Use |
|---|---|---|
| Correction rate per merchant and category | Category-change events | Fix the dictionary and retrain models |
| Link and sync success per institution and provider | Connection and sync events | Route new links to the best provider |
| Time from bank posting to visible in app | Sync timestamps | Freshness SLO |
| Share of users within budget | Aggregates | Product decisions |
| Spending trends by category (de-identified) | Aggregates | Insights content, research |
Per-user insights in batch. Insights such as "you spent 20% more on dining than your 3-month average" or "your phone bill went up by $10" are cheap per user but need history. A nightly job per shard computes them for users with changes and writes them to an insights table that the dashboard reads; nothing is computed on the read path.
Recurring transactions. Detecting subscriptions and bills is a small time-series problem per user and merchant: group transactions by merchant, look for regular intervals (weekly, biweekly, monthly, yearly) with similar amounts, and predict the next date and amount. Plaid offers this as an add-on (/transactions/recurring/get), which shows how common the need is. The output powers "bills due" alerts and "you have 9 subscriptions totalling $112 a month".
9. Storage at scale: partitioning, write throughput and tiering#
The write problem. About 2,000 transaction writes per second on average and 10,000 at the morning peak, plus aggregate updates, cursor updates and outbox rows: perhaps 3–4 database writes per transaction write event. One PostgreSQL primary on good hardware can handle thousands of small transactional writes per second, so a single primary would be overloaded at peak and leave no headroom for growth. The primer lists the options; here is how each fits:
| Technique | Fit here |
|---|---|
| Read replicas | Help reads, not writes; we use them for lists and search |
| Federation (split by function) | Natural: core data (users, connections, budgets), transactions, the vault and notifications each get their own database |
Sharding by user_id | The main answer for transactions and aggregates: all of a user's data on one shard |
| Denormalisation | Store merchant name and category id on each transaction, so lists need no joins |
| SQL tuning | Batch upserts per sync page, avoid unnecessary indexes, use IS DISTINCT FROM to skip no-op updates |
| NoSQL | A wide-column or key-value store (Cassandra, DynamoDB) with partition key user_id is a good fit if the team prefers it |
Sharding by user. With hash sharding on user_id into, say, 1,024 logical shards mapped onto 16–32 physical databases, each physical database takes about 300–600 transaction write events per second at peak, which is comfortable. Every query in the product is per user, so there are no cross-shard queries on the serving path; population queries go to the warehouse. Moving logical shards between databases rebalances load without changing the hash function (see Partitioning and Sharding and Pattern: Scaling Writes).
Batching writes. A sync page of 100–500 transactions should be written in one multi-row upsert inside one transaction, not 500 separate statements. This cuts round trips and log flushes by two orders of magnitude, and is the cheapest way to raise write throughput.
Hot users. A few users (small businesses, people with dozens of accounts) have far more transactions than average. Per-user sharding handles them fine as long as their partition stays reasonable; in a wide-column store, add the month to the partition key ((user_id, month)) so no partition grows without bound.
Tiering by age. Users look mostly at the last few months. The primer suggests keeping only about a month of transactions in the SQL database and the rest in the warehouse or object store. A more practical split for a product with "12-month trends" and search:
| Tier | Data | Store |
|---|---|---|
| Hot | Last 13 months of transactions, all aggregates | Sharded OLTP database, SSD |
| Warm | 13 months to 7 years | Partitioned tables on cheaper storage, or a columnar per-user archive in object storage, loaded on demand |
| Cold | Raw payloads, old event logs | Object storage with lifecycle rules |
Old months are read rarely; when a user scrolls back to 2021, the API can fetch that month from the warm tier with higher latency ("Loading older transactions…"). Monthly aggregates are kept forever in the hot tier because they are tiny.
Time-partitioned tables. Inside each shard, partition the transactions table by month (PostgreSQL declarative partitioning). Dropping or archiving a month becomes a metadata operation instead of a mass delete, and indexes stay small (see PostgreSQL in Practice).
The outbox. Events to the stream must reflect committed data exactly. Writing "transaction added" events from application code after the commit can lose events on a crash; writing them before the commit can emit events for data that was rolled back. The transactional outbox writes event rows in the same transaction as the data, and a relay (or change data capture from the write-ahead log, using Debezium for example) publishes them to Kafka (see Distributed Transactions: 2PC, Sagas and Outbox and Apache Kafka in Practice). Kafka topics are partitioned by user_id, so all events for one user are consumed in order by one consumer.
10. Privacy, consent and data rights#
A finance aggregator holds one of the most revealing datasets about a person: where they shop, what they earn, whom they pay, which doctor they see, what they drink. Privacy is not a feature to add later; it constrains the architecture.
Consent as data. Each connection has a consent record: what the user allowed (accounts, data types such as transactions, balances, identity), for which purpose ("budgeting and spending insights"), when it was granted, when it expires and when it was revoked. The record is checked by the scheduler (no sync without a valid consent) and by every consumer that uses the data for something new.
Purpose limitation. The CFPB's announcement of the Personal Financial Data Rights rule says third parties may collect, use and keep data only to deliver the product the consumer asked for, and gives the example of a lender that must not also use the data for targeted advertising. Europe's GDPR has a similar purpose-limitation principle. In design terms:
- Tag data flows with a purpose. The budgeting pipeline may read transactions; a marketing pipeline may not, unless the user opted in to "personalised offers", and the opt-in is recorded.
- The warehouse receives de-identified data only, and new uses of it need a review.
- Historically, Mint's Wikipedia article notes, its revenue came from referral fees for targeted financial product recommendations. That business model is exactly where consent design matters most: offers must use only data the user agreed to share for that purpose.
Revocation and deletion. The CFPB announcement says that when a person revokes access, data access must end immediately and deletion is the default practice. The unlink flow therefore:
- marks the connection
REVOKED(no new syncs from this instant), - calls the provider's revoke endpoint so the token is dead,
- deletes the credential and crypto-shreds its data key,
- deletes or anonymises the connection's accounts and transactions (with aggregates recomputed),
- deletes the raw payloads in object storage for that connection (lifecycle rules plus a deletion index from connection id to object keys),
- propagates a deletion event to the warehouse, caches and search index,
- records that deletion completed, for audit.
Deletion across many systems is a workflow, not one statement, so run it on a workflow engine with retries and a final verification step (see Pattern: Multi-Step Processes and Workflows).
Data minimisation. Request only the products we use (transactions and balances, not identity or account numbers unless a feature needs them). Mask account numbers. Do not keep raw payloads longer than needed for replay (for example 90 days hot, then delete or move to an encrypted archive with a short retention).
Access control inside the company. No engineer browses production transactions. Support staff see a user's data only after the user grants a support session, through a tool that logs every view. Production database access is just-in-time and reviewed. See Authentication and Authorization.
Data residency. EU users' data often must stay in the EU (or at least under GDPR safeguards), and some countries require local storage of financial data. With per-user sharding, residency becomes a placement rule: EU users' shards live in an EU region, with their own vault and KMS keys (see Multi-Region and Global Data).
Regulatory status. In the EU and UK, reading account data for others is a regulated activity (an AISP needs authorisation or registration, or must work under a licensed provider's umbrella). In the US, the Section 1033 rule sets the terms for authorised third parties. A design review should list which entity in the chain holds which licence, because it decides who signs the consent screens and who answers to the regulator.
11. Reliability when banks and aggregators fail#
The aggregator depends on systems that fail all the time. Thousands of institutions means that at any moment some are down, slow or changed. The design principle: a bank failure must degrade freshness, never availability or correctness.
Failure classes and responses.
| Failure | Detection | Response |
|---|---|---|
| One bank down or slow | Error and latency rate per institution | Circuit breaker per institution; delay that bank's jobs; show "Bank X is having problems" banner |
| One aggregator down | Error rate per provider | Delay jobs; for new links, route to a second provider for banks it supports |
| Bank changed login or MFA | Spike in login required errors for one bank | Do not mark every user NEEDS_REAUTH at once if it looks like a provider-side bug; wait for confirmation, then prompt users |
| Consent expiry wave | Many connections from one country expire on the same day (often 90 days after a launch campaign) | Pre-expiry reminders spread over two weeks |
| Webhook storm | Millions of webhooks after a provider backlog clears | Webhook receiver only enqueues; coalesce by connection (one pending job per connection) |
| Our database slow | Write latency, consumer lag | Back pressure: pause scheduled and backfill lanes |
Coalescing jobs per connection. Many triggers can fire for the same connection within minutes: a webhook, the daily schedule and a user refresh. Running three syncs is wasted money and can cause concurrent cursor updates. Keep at most one queued and one running job per connection: when a new trigger arrives, if a job is already queued, raise its priority instead of adding another; if one is running, set a "run again after" flag. A lease per connection (a row lock or a Redis key with a TTL) stops two workers syncing the same connection at once (see Pattern: Dealing with Contention).
Webhooks are hints, not data. Webhooks can arrive late, twice or out of order, and some never arrive. So a webhook only says "something may have changed for connection X"; the worker always pulls the real changes with the cursor. Duplicate and out-of-order webhooks then cost at most a wasted delta pull. The daily scheduled sync remains as a safety net for lost webhooks. Verify webhook signatures and reject old timestamps to block forged ones.
Balance reconciliation: catching missing transactions. The provider reports account balances as well as transactions. For an account, the balance change between two syncs should equal the sum of posted transactions in between:
balance_now − balance_before = − Σ (posted outflows) + Σ (posted inflows)
If the two differ, something is missing (a transaction we never received), duplicated, or the bank's data is inconsistent. Run this check per account after every sync; a mismatch triggers a wider re-sync (a full history pull for recent weeks) and, if it persists, a data-quality ticket against the provider. This one cheap invariant catches most silent data loss. It is the same idea as reconciling a ledger against a bank statement, described in the payment system case study.
Monitoring the product, not only the servers. Service-level objectives for this system:
| SLO | Example target |
|---|---|
| Dashboard availability | 99.9% of requests succeed |
| Dashboard latency | p99 under 300 ms |
| Freshness | 95% of active connections synced in the last 26 hours |
| Link success rate | Above 85% overall, tracked per institution and provider |
| Sync success rate | Above 98% for connections not in NEEDS_REAUTH |
| Pending-to-visible delay | 95% of new bank postings visible within 6 hours of the provider having them |
| Duplicate rate | Under 1 in 100,000 transactions (measured by balance checks and user reports) |
| Correction rate | Tracked per release; alert on a 20% relative jump |
See Observability: Logs, Metrics and Traces.
Disaster recovery. The core and transaction databases replicate to a second region; the vault and KMS keys are replicated too (a vault without its keys is a pile of random bytes). Because raw payloads are in object storage with cross-region replication, even a total loss of the transaction store can be rebuilt by replaying raw data, and a missing tail can be re-pulled from providers with old cursors or date ranges. Banks, in a sense, are our backup: the data can always be fetched again, which makes recovery point objectives for transactions less critical than for user edits (categories, notes, rules, budgets), which exist only with us. See Disaster Recovery and Backups.
12. Balances, net worth, currencies and investments#
Balances. Each account has a current balance and, for deposit accounts, an available balance (current minus holds), and for credit cards a limit and a statement balance. Store the latest values on the account and a daily balance snapshot table (account_id, date, current, available), which powers balance history charts without replaying transactions.
Net worth. Net worth = sum of asset balances (cash, investments, property estimates) minus liabilities (cards, loans, mortgages), each converted to the user's home currency. Compute it per day from the snapshots; a month of daily points per user is tiny. Watch the sign conventions: providers report credit card balances as positive amounts owed, and amounts on transactions may be positive for money out (Plaid's convention) or for money in (some banks). Normalise all of them at the connector boundary into one internal convention, and test it per provider.
Currencies. A user may hold accounts in several currencies. Rules that avoid confusion:
- Store every amount in its original currency with integer minor units (cents, pence, yen have zero decimals, some currencies have three).
- Convert for display and for budgets at a daily reference rate, and store the rate used for each month's aggregate so last month's numbers do not change every time exchange rates move.
- A foreign card purchase often has a pending amount in one currency and a posted amount that includes conversion and fees; matching tolerances must allow for this.
Investments and loans. Investment accounts have holdings (security, quantity, price) and investment transactions (buy, sell, dividend). They do not fit the spending model: a stock purchase is not spending. Keep them in separate tables, count only cash movements into and out of the account in cash-flow views, and value holdings with daily prices for net worth. Loans need principal, rate and payment schedule; the payment from checking is a transfer to the loan, partly principal (not spending) and partly interest (a cost). These distinctions matter for correct budgets, so the categoriser treats transfers and investment flows as a separate class (deep dive 5).
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Morning sync herd | Millions of jobs start at once; providers rate-limit us; database write spikes | Stable hashed slots with jitter, time-zone spreading, per-institution budgets, webhook-driven sync |
| A large bank or aggregator outage | Millions of connections cannot sync; retries pile up | Circuit breaker per institution and provider, delayed jobs instead of retries, "data as of" banners, second provider for new links |
| Credential vault breach | Tokens or passwords for millions of users exposed | Envelope encryption, KMS-only unwrap with audited roles, tokens instead of passwords, crypto-shredding, anomaly alerts on unwrap rates |
| Duplicate transactions | Wrong totals, false budget alerts, lost trust | Unique key on source id, idempotent upserts with the cursor in the same commit, pending-to-posted linking, balance reconciliation |
| Missing transactions | Budgets too low, user confusion | Balance-change check per sync, scheduled safety-net sync, full re-pull on mismatch |
| Event replay or double processing in aggregates | Totals counted twice | Event ids recorded with the aggregate update, versioned absolute events, nightly batch recomputation |
| Hot user partitions | One shard or partition slows down | Partition by user plus month in wide-column stores, monthly table partitions, archive old months |
| Mass re-categorisation after a model release | Event flood, cache invalidations, budget alert noise | Throttled backfill lane, suppress threshold alerts for batch recategorisations, shadow-test the model first |
| Webhook storm after a provider backlog | Receiver overwhelmed, duplicate jobs | Receiver only verifies and enqueues, one queued job per connection, coalescing |
| Consent-expiry wave | Many connections break on the same day | Pre-expiry reminders spread over time, easy re-consent, track expiry per cohort |
| Dashboard cache stampede after morning syncs | Database read spike | Cheap precomputed rebuilds, single-flight for hot keys, refresh-ahead for the most active users |
| Analytics queries on production | Slow syncs and dashboards for everyone | Separate warehouse fed from the stream, de-identified, no ad-hoc queries on OLTP shards |
What Interviewers Expect#
Mid-level. Lay out the main path: link an account, fetch transactions through an aggregator, store them, categorise them, compute monthly spending and check budgets. Put extraction on a queue so the web tier stays fast. Use a seller-to-category lookup and let the user override it. Recognise that the system is write-heavy (about 2,000 writes per second against 200 reads) and that dashboards should read precomputed aggregates through a cache. Notice that a password hash is useless for logging in to a bank.
Senior. Explain the three connection methods (screen scraping, aggregators, OAuth open-banking APIs) and their security and reliability trade-offs. Store secrets with envelope encryption and a KMS, separate from the main database. Design an incremental, cursor-based sync that stores data and cursor in one transaction, with idempotent upserts and pending-to-posted linking. Schedule syncs only for active users, with jitter, priority lanes and per-institution rate limits. Maintain aggregates from events with dedupe and an exactly-once alert key. Shard by user so all of a user's checks stay in one partition, tier old data, and keep analytics in a warehouse.
Staff and above. Treat the providers as an unreliable, costly, regulated ecosystem: route links per institution by measured success, plan for consent expiry and regulatory change (PSD2, the UK CMA order, the US Section 1033 rule), and design revocation and deletion as audited workflows. Quantify cost (provider fees per refresh, sync volume) and use it to shape the product (refresh limits, webhook-driven sync). Define product-level SLOs (freshness, duplicate rate, correction rate) and invariants (balance reconciliation, sum checks between stream and batch). Discuss the Lambda-style speed and batch layers for spending totals, crowdsourced categorisation with abuse controls, and the trust failures (the 2010 stored-password controversy, aggregator consent lawsuits) that shaped the industry.
Deep Dive: sizing the system, tier by tierShow
The capacity section gave totals. Here we turn them into machines, to show where the real costs are.
Sync workers. At the busiest window, about 400 sync jobs start per second and each spends about 3 seconds waiting on a provider, so about 1,200 jobs are in flight (Little's law). Sync workers are I/O-bound: an asynchronous worker (Go, Node.js, Java with virtual threads, Python asyncio) can hold 100–200 outstanding provider calls on 2–4 cores. So 10–20 worker instances cover the peak, with autoscaling on queue depth and a floor of a few instances per zone. CPU goes mostly to TLS, JSON parsing and normalisation: about 1–2 ms per transaction, so 10,000 transaction writes per second at peak need roughly 10–20 cores, spread over the same workers.
KMS calls. Each sync decrypts one token, which means one unwrap call to the KMS: about 150 per second on average and 400 at peak. Managed KMS services have per-account request quotas, typically in the thousands per second, and each call adds a few milliseconds. That is fine at this scale, but two patterns matter as it grows:
- Short-lived DEK caching in worker memory (for example 5 minutes, bounded size) cuts KMS calls when several jobs for the same connection run close together. It slightly increases exposure if a worker's memory is dumped, so keep the window short and the cache small.
- Per-region KMS keys spread load and support data residency.
Transaction store. About 10,000 transaction write events per second at peak, each costing 3–4 row writes (transaction, outbox, cursor, sometimes an aggregate), so about 35,000 row writes per second at peak. Batching per sync page means far fewer commits: with an average of 15 changed transactions per sync, 400 syncs per second produce about 400–600 commits per second, each writing a batch. With 16 physical PostgreSQL primaries, each handles about 2,000–2,500 row writes per second at peak, a comfortable load for a well-tuned primary with NVMe disks. Each has one synchronous standby in another zone and one or two asynchronous replicas for reads.
Storage per primary: 13 hot months × 1.1 TB per month ÷ 16 ≈ 900 GB each, plus indexes already counted in the 600-byte estimate. Comfortable. Growth to 50 million users means 64–80 primaries, which is why we start with 1,024 logical shards: we move logical shards to new machines rather than re-hashing.
Event stream. About 10,000 change events per second at peak, plus categorised events and alerts: say 25,000 events per second of about 1 KB each, which is 25 MB/s. A Kafka cluster of 6–9 brokers handles that easily, with replication factor 3 and 7 days of retention (about 15 TB on disk with replication). Partition count: 128–256 partitions per main topic, keyed by user_id, so consumer groups can scale out to that many consumers.
Category Service. Each transaction needs normalisation (regular expressions, a few hundred microseconds), a dictionary lookup (in memory) and sometimes a model score (about 1 ms for a gradient-boosted tree). About 10,000 per second at peak means roughly 10–20 cores, so a handful of instances. The merchant dictionary's hot set (a few million merchants and aliases, about 1 GB) is loaded into each instance's memory and refreshed every few minutes from the database.
Budget Service. One aggregate update per categorised transaction, executed on the user's shard: the same 10,000 per second at peak, already counted in the transaction store's budget above if aggregates live on the same shards.
Cache. Dashboards for active users: 4 million × about 10 KB ≈ 40 GB, plus sessions and recent-transaction lists. A Redis cluster with 6 shards of 16 GB (plus replicas) holds it. At 1,000 dashboard reads per second with an 85–95% hit rate, only 50–150 per second rebuild from the database, trivial for 16 primaries.
Raw store and warehouse. About 540 GB of compressed raw payloads a month, kept 90 days hot (1.6 TB), and about 300 GB a month of de-identified Parquet in the warehouse. Small by data-warehouse standards.
Summary.
| Tier | Size at 10 M users |
|---|---|
| Sync workers | 10–20 instances (I/O-bound), autoscaled |
| Connector Gateway | 4–8 instances plus a Redis cluster for token buckets |
| Credential Vault | 3 instances plus its own replicated database (about 30 GB) and KMS |
| Transaction store | 16 primaries, 16 synchronous standbys, 16–32 read replicas |
| Event stream | 6–9 Kafka brokers |
| Category, Budget, Notification services | 3–10 instances each |
| Cache | Redis cluster of about 100 GB with replicas |
| Raw store and warehouse | Object storage plus a managed warehouse |
The lesson matches the capacity section: compute is cheap here; the real limits are provider concurrency and cost, write throughput on the transaction store, and the security of a small vault.
Deep Dive: the numbers behind matching, categorisation and crowd votesShow
How much does a false pending-to-posted match hurt? Suppose a user has two $4.50 coffees pending at the same café on the same day and one of them posts. Matching it to the wrong pending entry is harmless (both are identical). Matching a posted $50.52 dinner to an unrelated pending $42.10 lunch at a different restaurant is harmful: the lunch disappears and the dinner's note is lost. That is why the matcher requires the same merchant (or very high description similarity) and allows a large amount tolerance only for merchant categories where it is expected (restaurants, fuel, hotels, car rentals). A simple expected-cost view helps choose the threshold: if a wrong match costs 10 times more trust than a missed match (a missed match just shows a pending item until it times out), choose a threshold where the matcher is right at least 10 times more often than it is wrong among the pairs it accepts.
Accuracy compounds through budgets. If the categoriser is 95% accurate per transaction and a user has 60 transactions a month, the expected number of wrong categories is 3 a month, and the chance that a month has none wrong is 0.95^60 ≈ 4.6%. Nearly every user will see at least one mistake every month. So accuracy improvements matter less than making corrections easy and permanent (rules, "apply to similar"), because a correction removes that mistake for all future months. At 98% accuracy the expected number of mistakes falls to 1.2 a month; the chance of a clean month rises to about 30%.
Dollar-weighted accuracy. A wrong category on a $3 coffee does not matter; a wrong category on a $2,000 rent payment ruins the housing budget. Measure accuracy weighted by amount as well as by count, and give large, recurring transactions extra attention (ask the user to confirm the category of a new large recurring payment once).
How many crowd votes are enough? Suppose a merchant's current default is "Shopping" and users keep moving it to "Groceries". Treat each correction as a vote. If we change the default when at least 70% of n votes agree, how likely are we to be fooled if the true share is only 50% (users are split)? With n = 10, the probability that 7 or more out of 10 agree by chance at a 50% true rate is about 17%. With n = 50, the probability that 35 or more agree is about 0.3%. So a minimum of about 50 distinct users per change, plus the 70% majority, makes accidental flips rare, and requiring distinct users and accounts older than a few weeks makes deliberate gaming expensive.
Selection bias in corrections. If the model is right 95% of the time, most users never touch the 95%, and corrections come from the 5%. A merchant with 1,000 transactions and 20 corrections to "Groceries" does not mean 2% of its transactions are groceries; it means 20 users disagreed with the default. Compare corrections with the number of users who saw and kept the default (exposure), not with transaction counts.
Pending budgets and false alarms. If 10% of pending amounts change by more than 20% when they post (tips, fuel holds, hotel deposits), firing the 100% budget alert on pending amounts will produce a share of false alarms proportional to how close users run to their limits. A user who runs at 95% of budget with a pending $60 fuel hold that settles at $38 receives an over-budget alert that is withdrawn the next day. The policy in deep dive 6 (alert on posted amounts, or on pending above a size threshold, and skip fuel holds) removes most of these.
Sync freshness math. If the provider checks a bank on average 2 times a day and we sync on its webhook within a minute, the expected delay from "bank has the transaction" to "user sees it" is about 6 hours (half the 12-hour gap), plus processing. If we instead poll the provider once a day at 6 a.m. without webhooks, the expected delay is about 12 hours, and a transaction posted at 7 a.m. waits 23 hours. Webhooks double freshness for free; forced refreshes on app open give near real time only for users who are actually looking.
Cost of a refresh button. Suppose 4 million active users open the app 1.5 times a day, and we trigger a forced refresh on every open. That is 6 million forced refreshes a day. With a per-refresh fee assumed at one cent, that is $60,000 a day. Limiting forced refreshes to opens where the last sync is older than 6 hours, and to one per connection per 15 minutes for manual pulls, cuts this by a large factor with little impact on perceived freshness.
Deep Dive: one user, one week, end to endShow
Asha installs the app on a Sunday evening.
- Sunday 20:05. Linking. Asha links a checking account and a credit card at one bank (one connection, two accounts) and a savings account at an online bank (a second connection). The first bank supports OAuth: Asha logs in on the bank's page, approves sharing for both accounts, and comes back to the app. The online bank does not, so the aggregator's widget shows its credential form and handles a one-time SMS code. Our servers receive two public tokens and exchange them for access tokens, which go into the vault encrypted under two fresh data keys. The app shows three accounts with balances within about 8 seconds.
- Sunday 20:06. Initial sync. Two initial-sync jobs run in the interactive lane. The providers return about 30 days of transactions within a minute (about 140 transactions), and the rest of 2 years of history over the next 20 minutes, announced by a webhook. Workers store raw payloads, upsert the transactions and write outbox events. The categoriser assigns categories: 92% from merchant defaults and user-independent rules, 6% from the model, 2% left as "Uncategorised".
- Sunday 20:30. Budget suggestion. The income estimator finds a biweekly payroll deposit of $2,150 (about $4,660 a month) and proposes a budget from the template for that tier, blended with Asha's actual three-month averages. Asha lowers "Shopping" from $930 to $500 and "Food" from $930 to $800, closer to what they actually spend. Two rows go into
budget_overrides; the other eight categories follow the template. - Monday 06:41. Scheduled sync. Asha is active, so both connections get a morning slot (06:41 and 06:53 local time, from a hash of the connection ids). The bank reports Friday's dinner as posted with a tip; the pending row is replaced in place (Flow 4), and the dining total rises by the tip. A balance check passes: the checking balance change equals the sum of posted transactions since the last sync.
- Monday 08:15. Correction. Asha opens the app (dashboard from cache, 40 ms) and sees "COSTCO WHSE" as "Shopping". They change it to "Groceries" and tick "apply to similar". A rule is stored; 14 past Costco transactions move to Groceries in a background job, and the monthly totals for each affected month are adjusted. An anonymised vote for "Costco → Groceries" goes to the crowd pipeline.
- Wednesday 19:20. On-demand refresh. At the shop, Asha pulls to refresh. The last sync was 13 hours ago, so a forced refresh is allowed. The provider contacts the bank; 20 seconds later a webhook arrives, a delta pull returns today's pending grocery purchase of $86, and the app updates.
- Wednesday 19:21. Alert. The grocery purchase takes Food from $612 to $698 of $800, crossing 80%. The Budget Service emits the key (Asha, 2026-11, Food, 80%); the Notification Service sends "You have used 87% of your Food budget, with 10 days left". A Kafka consumer restart replays the event an hour later; the key already exists, so nothing is sent.
- Thursday 02:00. Nightly jobs. The batch job recomputes November's totals for all user-months that changed today, including Asha's, and finds they match the stream totals. The insights job notices that Asha's streaming subscriptions have risen to $47 a month across four services and writes an insight card.
- Friday 11:00. A bank breaks. The online bank changes its login page. The aggregator's connector fails for every user of that bank. Our circuit breaker for that institution opens after the error rate passes 50%; jobs for that bank are delayed, not retried. Asha's savings account shows "Updated 1 day ago. The bank is having connection problems". The dashboard still works. When the aggregator fixes the connector on Saturday, the breaker closes and syncs resume with the old cursor, so nothing is lost.
- Sunday. Unlink. Asha closes the online savings account and unlinks it in the app. The connection becomes
REVOKEDinstantly, the provider's token is revoked, the data key is deleted (making any backup copy of the token unreadable), and a deletion workflow removes the account's transactions and raw payloads and recomputes Asha's aggregates. The deletion is recorded for audit.
Every step uses only the mechanisms in the design: tokens instead of passwords where possible, encrypted secrets, cursors and idempotent upserts, events with keys, precomputed aggregates, and circuit breakers. No step needed a cross-user query or a synchronous call to a bank on the read path.
Deep Dive: a 45-minute interview plan for this problemShow
| Minutes | What to do |
|---|---|
| 0–5 | Clarify: account types, read-only or money movement, freshness, who is active, overrides, budgets and alerts, scale |
| 5–10 | Numbers: 10 M users, 30 M accounts, 5 B transaction writes a month (2,000 per second), 500 M reads (200 per second), 10:1 write to read; storage per month |
| 10–20 | High-level design: link flow with tokens, sync queue and workers, raw store, transaction store, categoriser, budget service, notifications, read API with cache, warehouse |
| 20–25 | Data model: transactions keyed by user, unique source id, category source, monthly spending, budget overrides; no credentials in the main DB |
| 25–40 | Deep dives (choose with the interviewer): credential security, incremental sync and dedupe, scheduling and rate limits, categorisation, exactly-once alerts |
| 40–45 | Bottlenecks, failure handling, privacy and evolution |
Follow-up questions to prepare for.
- Why can you not store a hash of the bank password? Because we must present it to the bank; hashes are one-way. Use tokens, or encrypt with envelope encryption under a KMS.
- How do you avoid duplicates when a sync is retried? Unique key on the provider's id, idempotent upserts, cursor saved in the same transaction.
- A pending transaction posts with a different amount. What happens? Replace in place, keep user edits, adjust aggregates by the difference.
- How do you keep sync costs down? Sync only active users daily, use webhooks, coalesce jobs, limit forced refreshes.
- A bank is down for a day. What does the user see? Last known data with a timestamp; no errors on the dashboard; the circuit breaker stops retries.
- How do you categorise an unknown merchant? Normalise, fuzzy-match, then a model on text and amount features; low confidence asks the user.
- A user changes a category. What changes? The transaction, the monthly totals, an optional rule and the crowd votes; never overwritten later.
- How do you make sure a budget alert fires exactly once? Atomic before-and-after totals, a deterministic alert key with a unique constraint.
- The system has 10 times more writes than reads. How does that shape it? Asynchronous ingestion, batching, sharding by user, precomputed aggregates for reads.
- How do you run analytics on all users without hurting production? Stream events to a de-identified warehouse; batch jobs over raw logs.
- How do you delete a user's data, including backups? Revoke, delete, crypto-shred keys, workflow across all stores, audit record.
- How would you support Europe? AISP licensing or a licensed partner, open-banking APIs, consent expiry tracking, EU data residency.
Deep Dive: variants of the problemShow
"Design the aggregator itself" (Plaid- or Yodlee-like). Now we are the provider. The core changes: thousands of institution connectors (official APIs, partner agreements, scraping), a connector health system that detects breakages within minutes, credential and MFA handling at the edge, our own polling schedule per institution (balancing freshness against bank load), webhooks to thousands of client apps, per-client rate limits and billing, data enrichment (merchant names, logos, categories) sold as a product, and a consent and compliance layer that clients rely on. The scale shifts from one app's 30 million accounts to hundreds of millions, and the hardest part becomes operations on connectors, not storage.
"Design expense tracking for small businesses." Transactions have receipts, tax categories and approvals. Each business has several users with roles. Categories map to an accounting chart of accounts and must export to accounting software. Duplicates across card feeds and bank feeds are more common. Correctness and audit trails matter more than speed of alerts.
"Design cash-flow underwriting for a lender." The lender reads 12–24 months of transactions once, at application time, with explicit consent. The priorities are income verification, recurring obligations, overdraft frequency and a defensible model. Freshness matters only for the one pull; the data must be retained for regulatory record-keeping, and purpose limitation means it cannot be reused for marketing.
"Design a shared household budget." Two or more users share some accounts and budgets but not others. The data model needs households with membership, per-account sharing settings, and aggregates per household as well as per user. Privacy rules are subtle: a partner may see the joint account but not the other's personal card.
"Design it for a single country with open banking everywhere" (for example the UK). Scraping disappears; every connection is an OAuth token with a consent expiry. The hard problems become consent renewal journeys, bank API quality differences and payment initiation (paying bills directly from the app), which brings in strong customer authentication and the payment concerns of the payment system case study.
Small scale (100,000 users). One PostgreSQL primary with a replica handles about 20 writes per second on average; a single worker process runs syncs; categorisation runs in the same process; a nightly cron recomputes aggregates. One aggregator, no warehouse (a read replica answers analytics). The security design (vault, KMS, tokens) does not shrink: it must be right from day one.
Deep Dive: how the product evolves from v1 to v3Show
v1: launch (up to 1 million users). One aggregator for all banks. A monolith with a job queue for syncs, PostgreSQL for everything (transactions partitioned by month), a separate small vault database with KMS-wrapped tokens, nightly scheduled syncs for active users plus refresh on demand, a merchant dictionary of the top 50,000 sellers plus the provider's categories, budgets from templates with overrides, alerts from a nightly job. What must be right from day one: tokens instead of passwords, envelope encryption, idempotent upserts with source ids, cursor and data in one commit, category_source so user choices are never overwritten, and a deletion path.
v2: scale (1 to 20 million users). Split services (connections, sync, categorisation, budgets, notifications, read API); shard the transaction store by user; add Kafka with an outbox; event-driven aggregates and real-time alerts; webhook-driven sync with daily safety nets; priority lanes and per-institution rate limits; a second aggregator and per-institution routing; direct open-banking connections in markets with good APIs; a categorisation model trained on corrections; Redis dashboards; a warehouse with de-identified data; balance reconciliation and product SLOs.
v3: platform (20 million users and beyond, several countries). Regional deployments for data residency, with per-region vaults and keys; consent management for several regimes; recurring-bill detection and cash-flow forecasting; household sharing; insights generated by a feature pipeline; an experimentation platform for budget suggestions and nudges; possibly payment initiation (pay a bill, move savings), which turns the read-only product into a regulated payment service and requires the payment system's idempotency, ledger and reconciliation disciplines. Each step adds features at the edges while keeping the core (tokens in a vault, cursors with idempotent upserts, events with keys, precomputed aggregates) unchanged.
Key Takeaways#
- Never hold a password you can avoid. Prefer bank OAuth and aggregator tokens; anything you must keep is encrypted (never hashed) with envelope encryption, keys in a KMS backed by HSMs, in a separate vault.
- The data belongs to the banks, so sync is the core problem. Use cursors, store data and cursor in one commit, upsert idempotently on the provider id, and link pending to posted as one logical transaction.
- Sync only what someone will look at. Daily syncs for users active in the last 30 days, webhooks instead of polling, coalesced jobs, priority lanes and per-institution rate limits keep cost and bank load under control.
- Categories must never fight the user. Merchant normalisation, user rules, merchant defaults and a model, with a recorded source so manual choices are never overwritten; corrections feed a crowd pipeline with vote thresholds.
- Precompute what the screens show. Monthly spending aggregates maintained from events, cached dashboards with invalidation on change, and "last updated" times so bank outages degrade freshness, not availability.
- Alerts fire once by construction. Atomic before-and-after totals and a deterministic alert key with a unique constraint make retries and replays harmless.
- Write-heavy means shard by user. 2,000 writes per second on average against 200 reads: batch writes, shard on
user_id, keep every dedupe and aggregate check inside one partition, and tier old months. - Speed layer plus batch layer. Stream aggregates for the dashboard, nightly recomputation from raw logs to correct drift, and a de-identified warehouse for population analytics.
- Invariants catch silent errors. Balance change equals the sum of posted transactions; stream totals equal batch totals; duplicate and correction rates are product SLOs.
- Consent, revocation and deletion are architecture. Purpose-tagged data flows, consent expiry per connection, and deletion workflows with crypto-shredding are what open-banking rules and user trust demand.