Inside the Data Layer: Storage, Consistency and Performance

Inside the Data Layer: Storage, Consistency and Performance

Explore how databases store and manage information, using transactions, ACID properties, SQL, indexing, replication, consistency, and caching to build reliable and scalable systems.

Series: The Anatomy of Modern Systems: From Architecture to Scalability (5 articles)

  1. …
  2. 4
    Inside the Data Layer: Storage, Consistency and Performance This article
Every payment leaves a record. Every account has a balance. Every transaction needs to be stored, retrieved, and protected against failures.
But what happens when thousands of users make payments at the same time? How does a system ensure that money is never deducted twice, data stays consistent, and transaction history loads quickly?
This is where the database layer comes in. In this post, we'll explore how databases organize information, handle transactions, improve query performance, and stay reliable as applications grow.

Database Fundamentals: Tables, Keys and Normalization

Here is a simple payment database with two tables:
customers transactions
--------- ------------
customer_id (PK) transaction_id (PK)
name from_customer_id (FK → customers)
balance to_customer_id (FK → customers)
amount
status
created_at
A primary key (PK) uniquely identifies a record in a table. A foreign key (FK) links a record to a record in another table by referencing its key. One customer can have many transactions.
Normalization organizes data to reduce duplication and improve consistency, usually by splitting related data into separate tables. Sameer's name is stored once in  customers , and every transaction refers to him by  customer_id  instead of copying his name each time. Change his name once and it is correct everywhere.

Ensuring Data Integrity with ACID Transactions

A database transaction groups operations into one logical unit: either all of them succeed or the whole thing is rolled back. This is how Riya's payment stays safe:
BEGIN;

UPDATE customers SET balance = balance - 500
WHERE customer_id = 'riya' AND balance >= 500;

UPDATE customers SET balance = balance + 500
WHERE customer_id = 'sameer';

INSERT INTO transactions
(transaction_id, from_customer_id, to_customer_id, amount, status)
VALUES ('TXN123', 'riya', 'sameer', 500, 'SUCCESS');

COMMIT;
If anything fails in the middle, the database runs  ROLLBACK  and none of the changes are kept. The  balance >= 500  condition stops Riya from spending money she does not have.
Safe transactions follow four guarantees, known as ACID:
Property
Meaning
In our payment
Atomicity
All operations succeed or none do
Debit and credit both happen, or neither does
Consistency
The database stays in a valid state
Balances never go negative
Isolation
Concurrent transactions do not interfere incorrectly
Two simultaneous ₹500 payments from an ₹800 balance cannot both succeed
Durability
Committed data survives a failure
After "success", a crash does not undo it

Working with Data Using SQL

A few queries you will use constantly:
-- Riya's successful payments, newest first
SELECT * FROM transactions
WHERE from_customer_id = 'riya' AND status = 'SUCCESS'
ORDER BY created_at DESC;

-- How many transactions per status?
SELECT status, COUNT(*) FROM transactions GROUP BY status;

-- Only statuses with more than 100 transactions
SELECT status, COUNT(*) FROM transactions
GROUP BY status HAVING COUNT(*) > 100;

-- Every customer, with their payments if any
SELECT c.name, t.amount
FROM customers c
LEFT JOIN transactions t ON c.customer_id = t.from_customer_id;
  • WHERE filters individual rows before grouping. HAVING filters groups after  GROUP BY .
  • INNER JOIN returns only rows that match in both tables. LEFT JOIN returns every row from the left table, plus matches from the right. A customer with no payments still appears.
  • Aggregate functions such as  COUNT() ,  SUM() ,  AVG() ,  MIN()  and  MAX()  summarize groups of rows.
  • DELETE removes selected rows, TRUNCATE removes all rows from a table, and DROP removes the table itself.

Improving Query Performance with Indexing

Without help, the database scans the whole  transactions  table to find Riya's payments. An index is a data structure that lets it jump straight to matching rows.
CREATE INDEX idx_txn_customer
ON transactions (from_customer_id, created_at);
Trade-off: indexes speed up reads, but they use storage and add work to every insert and update. Index the columns you search by, not everything.

Scaling Database Performance with Replication

Replication keeps copies of the data on multiple database servers, improving availability and supporting recovery. The usual setup has one primary that accepts writes and one or more replicas that copy it and serve reads.



Synchronous replication
Asynchronous replication
How it works
Primary waits for the replica to confirm
Primary does not wait
Consistency
Stronger
Replica may be briefly behind
Latency
Higher
Lower
With asynchronous replication, a replica can lag behind the primary. That is called replication lag, and it leads to our next topic.

Understanding Data Consistency

Eventual consistency means different copies may briefly hold different values but will agree once replication catches up. Strong consistency means everyone sees the latest committed value.
  • Needs strong consistency: the balance check before a payment, and the final payment status.
  • Can tolerate eventual consistency: transaction history screens, analytics, monthly reports.
The CAP theorem states the underlying trade-off: when a network partition splits a distributed system, it generally has to prioritize either consistency or availability. For moving money we prioritize correctness. A user seeing "try again" is better than a wrong balance.

Improving Performance with Caching

A cache stores frequently accessed data in a faster layer, so the application does not query the database every time.


Benefit: lower latency and less load on the database. Trade-off: cached data can go stale. Set expiry times, and never cache a value you need to be exact.
Good to cache
Do not cache
Merchant names and profiles
The balance used to approve a payment
Frequently viewed reports
Final payment status

Putting the Data Layer Together

Our payment app now keeps  customers  and  transactions  in a relational database. Every payment runs inside one transaction, so Riya's debit and Sameer's credit succeed or fail together. We index  transactions  by customer and date so history loads quickly.
To scale, we send payments to the primary database, serve history and reports from replicas, and cache rarely changing data such as merchant details.
Writes + balance checks → Primary DB
History + reports → Replicas
Merchant details → Cache → Replica on a miss

Common mistakes

  • Doing the debit and credit as separate steps. A crash in between loses money. Use one transaction.
  • Reading the balance from a lagging replica to approve a payment.
  • Indexing every column. Writes slow down and storage grows.
  • Caching without an expiry plan. Users see stale data indefinitely.
  • Running DELETE or TRUNCATE without a WHERE or a backup in production.

Key takeaways

  • A transaction makes multi-step changes all-or-nothing, and ACID describes the guarantees.
  • Primary and foreign keys link tables, and normalization reduces duplication.
  • Indexes speed up reads at the cost of storage and slower writes.
  • Replicas scale reads and improve availability, but asynchronous replicas can lag.
  • Use strong consistency for money and eventual consistency for reporting.
  • Caches reduce load and latency, but can serve stale data.

Next up

In the next post, we'll explore how systems handle failures and unexpected situations using message queues, retries, circuit breakers, security controls, and monitoring to keep applications reliable.

Series: The Anatomy of Modern Systems: From Architecture to Scalability (5 articles)

  1. …
  2. 4
    Inside the Data Layer: Storage, Consistency and Performance This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article