Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Concept · 25 min · revision 1

Data-access antipatterns: chatty, over-fetching, busy and uncached

Recognise chatty I/O, extraneous fetching, a busy database, monolithic persistence and missing caching from query statistics and traces, and choose the structural fix for each, with its limits.

Contentsand lesson path

What you will learn

  • Recognize data-access antipatterns (chatty I/O, extraneous fetching, busy database, monolithic persistence, no caching) from traces and query metrics, and choose a structural fix for each.

01. Why it matters

The database is usually the hardest tier to scale. Application servers keep no state between requests, so you can add more of them. A database holds the data, so scaling it means replicas, partitions and difficult trade-offs, as database scaling shows. Yet many slow systems are not short of database capacity at all. They ask the database for the wrong things: too many small requests, too much data, work that is not data access, every kind of data in one place, or the same answer again and again.

Each of these five antipatterns has a signature, a pattern you can see in traces and query statistics, and a structural fix: a change to how the code uses data, not a bigger machine. The names come from Microsoft's catalogue of cloud performance antipatterns.

02. Count before you time

Timings change from machine to machine and from run to run. Counts do not: how many statements a request sends, and how many rows it pulls back. The script below builds a small orders table in SQLite, which ships with Python, and records every statement with set_trace_callback. Each function produces the same page, the newest 20 orders of customer 7 or their items, in a different way. Save it as access_patterns.py and run python3 access_patterns.py:

Python · access_patterns.py
"""Count what one page asks of the database: statements sent and rows fetched."""

import sqlite3

db = sqlite3.connect(':memory:')
db.executescript("""
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT, created_at TEXT);
CREATE TABLE items (order_id INT, qty INT, price_cents INT);
CREATE INDEX orders_by_customer ON orders (customer_id, created_at);
CREATE INDEX items_by_order ON items (order_id);
""")
db.executemany('INSERT INTO orders VALUES (?, ?, ?)', [
    (i, i % 500, f'2026-{1 + i % 12:02}-{1 + i % 28:02}') for i in range(1, 30001)])
db.executemany('INSERT INTO items VALUES (?, ?, ?)', [
    (i, n, 250 * n) for i in range(1, 30001) for n in (1, 2, 3)])
sent: list[str] = []
db.set_trace_callback(sent.append)  # called once for every statement sent
NEWEST = ('SELECT id FROM orders WHERE customer_id = 7'
          ' ORDER BY created_at DESC, id LIMIT 20')


def chatty() -> int:
    ids = [r[0] for r in db.execute(NEWEST).fetchall()]
    items = [db.execute('SELECT qty, price_cents FROM items WHERE order_id = ?',
                        (i,)).fetchall() for i in ids]
    return len(ids) + sum(len(rows) for rows in items)


def batched() -> int:
    ids = [r[0] for r in db.execute(NEWEST).fetchall()]
    marks = ','.join('?' * len(ids))
    items = db.execute(f'SELECT order_id, qty, price_cents FROM items'
                       f' WHERE order_id IN ({marks})', ids).fetchall()
    return len(ids) + len(items)


def filter_in_app() -> int:
    rows = db.execute('SELECT id, customer_id, created_at FROM orders').fetchall()
    mine = sorted((r for r in rows if r[1] == 7), key=lambda r: (r[2], r[0]))
    assert len(mine[-20:]) == 20
    return len(rows)


def filter_in_db() -> int:
    return len(db.execute(NEWEST).fetchall())


for name, fn in [('items: one query per order', chatty),
                 ('items: one query for all orders', batched),
                 ('newest 20: filter in Python', filter_in_app),
                 ('newest 20: WHERE and LIMIT in SQL', filter_in_db)]:
    sent.clear()
    rows = fn()
    print(f'{name:<34} queries {len(sent):>3}   rows fetched {rows:>6,}')
Expected output
items: one query per order         queries  21   rows fetched     80
items: one query for all orders    queries   2   rows fetched     80
newest 20: filter in Python        queries   1   rows fetched 30,000
newest 20: WHERE and LIMIT in SQL  queries   1   rows fetched     20

In PostgreSQL you get the same two counts per statement from the pg_stat_statements extension: calls (how many times the statement ran) and rows (how many rows it returned or changed), next to total_exec_time and mean_exec_time. Divide calls by the number of requests and you have statements per request; divide rows by calls and you have rows per call.

03. Chatty I/O and extraneous fetching: too many requests, too much data

Chatty I/O means many small requests where one larger request would do. The best-known case is the N+1 query: one query for a list, then one more for every item in it. The first two lines of the output fetch the same 80 rows, once with 21 queries and once with 2.

Every query costs more than its execution time: a network round trip, parsing and planning, and work in the driver and the server to start and finish it. A rough model is time spent travelling ≈ queries × round-trip time. Every number in it is an assumption you should measure on your own system. If an application server and its database are in the same data centre and a round trip takes 0.5 ms, 21 queries spend about 10.5 ms travelling and 2 queries about 1 ms. If the database sits in another region and a round trip takes 30 ms, the same page spends about 630 ms travelling, against 60 ms. An index makes each query faster but leaves the number of trips unchanged.

The signature: a trace with a row of sibling spans for the same statement; a statement in pg_stat_statements whose calls are a multiple of the request count, with a tiny mean time; high database CPU and connection activity for few rows. The pattern is not limited to SQL. One cache GET per key, one HTTP call per item to another service, and one INSERT plus one COMMIT per imported row are all chatty I/O.

The fix is to batch: an IN or = ANY list, a join, eager loading in an ORM (the SQLAlchemy N+1 lab shows this), multi-key reads such as Redis MGET, a batch endpoint, multi-row inserts or COPY inside one transaction. Batches have limits too: a list of 50,000 ids, a transaction that holds locks for minutes or a join that repeats every parent column for each child row becomes the next problem. Batch in chunks, and measure.

Extraneous fetching means fetching more data than the operation uses. The demo's third line pulls 30,000 rows to show 20. Other forms are columns nobody reads, such as SELECT * on a table with a large JSON or text column, and totals computed by loading every row into the application. The cost often appears far from the query: in network bytes, in memory and garbage collection, and in time spent turning rows into objects and objects into JSON.

The signature: rows per call far above what the response contains; large responses; memory that jumps on each request; traces in which converting and serialising the rows takes longer than the query. The fix is to let the database filter, sort, limit and aggregate, with indexes that support those operations (reading execution plans); to select only the columns you need; to paginate; and to shape API responses around what clients actually show. Do not overcorrect: fetching tiny pieces many times turns extraneous fetching into chatty I/O.

04. Busy database and monolithic persistence: work and data in the wrong place

Busy database means the database spends its CPU on work that does not need to happen there: formatting output for display, string processing, unit and currency conversion, or business rules in stored procedures that run on every request. The database is the hardest tier to scale, so its CPU time is expensive.

The signature: database CPU high while statement counts and rows per call look normal; a few statements dominate total_exec_time with a high mean; the plans of those statements are simple, and the cost is in functions they call. The fix is to move presentation and computation that does not need the data to the stateless application tier, which scales out cheaply. The limit is important: set-based work over many rows, such as filtering, joining and aggregating, belongs in the database. Moving it out creates extraneous fetching. A useful rule is that the database does what needs to be near the data, and the application does what needs to be near the user.

Monolithic persistence means one data store for every kind of data: orders, audit logs, click events, sessions, search and reports. These have different access patterns. Orders need transactions and random reads. Logs and events are append-only, written constantly and read in bulk. Reports scan large ranges. In one PostgreSQL server they share the CPU, the disks, the write-ahead log, the memory used to cache pages and the connections, so a burst of event inserts or a long report slows checkout.

The signature: the latency of core transactions rises and falls with an unrelated workload, such as a batch job or a burst of logging; statements that are not business data appear among the top statements by total time; the share of reads served from memory drops while reports run. The fix is to separate data by how it is used: events to a log or stream store, analytics to a replica or a warehouse fed by change data capture (a stream of every committed change), search to a search index (search indexing), short-lived sessions to a key-value store (storage selection covers the choice). The limits: each extra store is another system to run, back up and secure, and data in two stores must be kept in step without writing to both in the request. Split when measurements show contention, not because the diagram looks tidier.

05. No caching: the same answer, fetched again and again

No caching means fetching the same data again and again although it changes rarely and a slightly old copy is acceptable. The signature: the same statement with the same parameters near the top of calls; a dependency called once per request for a value that changes a few times a day; a read-to-write ratio in the hundreds or thousands.

Whether to cache is a measurement question: how often is the item read, how often does it change, how stale may it be, how many distinct keys are there, and what does a miss cost? Good candidates are read often, change rarely, tolerate some staleness and have a small key set. Poor candidates must be exact at the moment of use (the stock level when an order is placed), change with almost every read, or have so many keys that most lookups miss.

The usual fix is cache-aside (check the cache first; on a miss, read the database and store the result) with a time-to-live (TTL) equal to the staleness the business accepts. Caching brings its own problems, such as invalidation, stampedes and memory. The caching patterns lesson and the stampede lesson cover them, and lesson 04 of this skill adds a small stampede guard.

06. Check your understanding

Practice check · 3 questions

Data-access antipatterns

Three questions about signatures and structural fixes.

Q1. An online shop writes every page-view event into its main PostgreSQL database, about 4,000 inserts per second at peak, next to orders and payments. Checkout p99 rises whenever page-view traffic peaks, and the event insert is the top statement by total time. Which change addresses the cause?
Q2. Three frequent queries on a product site are listed below. Which is the best candidate for a cache with a 5-minute TTL? A: category tree, 2,500 calls/s, same parameters, edited a few times a day B: stock count, 300 calls/s, must be exact when an order is placed C: a user's cart, 900 calls/s, changes on most requests from that user
Q3. A product list page shows 24 items, but it is slow and the application's memory jumps on each request. You suspect extraneous fetching. Which measurement would confirm it before you change any code?
Practice only: not graded, not saved, not evidence.

07. Apply it

Continue the practice task. In the lab, the load generator prints the statements that ran most often. For the sample endpoint, or for an endpoint you own, list every statement it sends with its calls per request and rows per call, and mark which of the five antipatterns each shows, if any. For each one you mark, write the structural fix and the counter that should change when the fix works, for example statements per request from 21 to 2, or rows per call from 30,000 to 20.

08. Review prompt

Without looking back, name the five data-access antipatterns of this lesson. For each, describe its signature in traces or pg_stat_statements, its structural fix, and one way the fix can go too far. Then explain why counting statements and rows is a better first measurement than timing them.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check