All posts

Stop Making Your Database Do Work Nobody Asked For.

Our product list was slow. While debugging it, we pulled up the SQL for one page of the catalog. The response was 100 IDs and names. This was in the query:

NOT EXISTS (SELECT 1 FROM orders WHERE orders.product_id = products.id)

An order matters when a seller tries to delete a product. We keep the product around so the order still has something to point to. But the seller was just browsing the catalog.

That bit of SQL came from Product.is_deletable, a field we use in product settings to decide whether to show Delete. Loading a Product also loaded that field. By the time our list endpoint picked out the ID and name, Postgres had already worked out whether the product could be deleted. It did that for the whole page.

We kept the deletion rule where it was and changed when it runs. The field is deferred by default. The settings query asks for it with one line:

detail = detail.options(undefer(Product.is_deletable))

Now the orders table drops out of the catalog query, along with the four other tables used by the deletion rule. Opening settings still gives the seller the same answer in one query.

What that saves on a busy catalog

Take 500 reads a second, with 475 full catalog pages and 25 individual products opened in settings. The catalog accounts for 47,500 products a second. Every one of them used to carry the deletion check. Now only the 25 opened in settings do.

Each product can require up to five checks for related records. In this model, the maximum falls from 237,625 checks a second to 125, a 99.95% drop. The SQL tells us which work disappeared. How much sooner a seller sees the page still needs to be measured.

See the Python and SQL before and after
from sqlalchemy import and_, select
from sqlalchemy.orm import column_property

def deletion_eligibility(product_id):
    def has_reference(table, *conditions):
        return (
            select(1)
            .select_from(table)
            .where(table.c.product_id == product_id, *conditions)
            .correlate_except(table)
            .exists()
        )

    return and_(
        ~has_reference(orders),
        ~has_reference(subscriptions),
        ~has_reference(subscription_updates, subscription_updates.c.deleted_at.is_(None)),
        ~has_reference(trial_redemptions),
        ~has_reference(discount_products, discount_products.c.active.is_(True)),
    )

class Product(Base):
    __table__ = products
    is_deletable = column_property(deletion_eligibility(products.c.id))

Each subquery borrows the product ID from the outer query. correlate_except(table) keeps the child table inside the subquery even when the outer query also joins that table.

SELECT p.id, p.name,
       (NOT EXISTS (SELECT 1 FROM orders o WHERE o.product_id = p.id)
        AND NOT EXISTS (SELECT 1 FROM subscriptions s WHERE s.product_id = p.id)
        AND NOT EXISTS (SELECT 1 FROM subscription_updates u
                        WHERE u.product_id = p.id AND u.deleted_at IS NULL)
        AND NOT EXISTS (SELECT 1 FROM trial_redemptions t WHERE t.product_id = p.id)
        AND NOT EXISTS (SELECT 1 FROM discount_products d
                        WHERE d.product_id = p.id AND d.active IS TRUE)
       ) AS is_deletable
FROM products p
WHERE p.seller_id = :seller AND p.id > :cursor
ORDER BY p.id
LIMIT 100;

After

# On the Product model
is_deletable = column_property(
    deletion_eligibility(products.c.id),
    deferred=True,
    raiseload=True,
    expire_on_flush=False,
)

# In the settings endpoint
detail = (
    select(Product)
    .where(Product.seller_id == seller_id, Product.id == product_id)
    .options(undefer(Product.is_deletable))
)
SELECT p.id, p.name
FROM products p
WHERE p.seller_id = :seller AND p.id > :cursor
ORDER BY p.id
LIMIT 100;

On a freshly loaded catalog item, raiseload=True catches a serializer that accidentally reads the deferred field. expire_on_flush=False keeps an already loaded value across a flush. It can go stale. If an order arrives after settings loads, the delete transaction must still enforce the rule under concurrent writes.

Check the math or run the benchmark
At sustained loadBeforeAfter
Read requests per second500500
Products checked for deletion per second47,52525
Checks for related records per second (up to)237,625125
Checks for related records per day (up to)20.53 billion10.8 million

Each product contributes up to five checks. Multiply the per-second figure by 86,400 for a full day at that rate.

The reference system uses FastAPI, SQLAlchemy and PostgreSQL 17 on 8 vCPUs, 32 GB RAM and NVMe storage, with 1 million products, 10 million orders and 2 million subscriptions.

Run both mappings on the same dedicated database host and drive FastAPI from a separate machine. The experiment below assumes the routes accept the example cursor and seller parameters. Use separate list and detail response schemas in both versions. First verify that both return identical JSON for the same requests, including products with an order, only an inactive discount, or an active discount.

Start with two products from the test catalog. An order has a column called product_id. If it contains 2, that order belongs to Product 2.

ProductWhat’s in the database?What should settings show?
Product 2An order with product_id = 2Archive only. The order needs its product.
Product 15No order, subscription, update, trial or active discount uses itDelete is available.

That pair is enough to explain the change. When a seller opens settings for Product 2, the order matters. When they browse a list containing both products, all they need are the names. The benchmark repeats those two kinds of requests across a million products.

Generate the full test catalog in PostgreSQL

Use an empty test database with the tables from the example and automatically generated IDs for the related rows. PostgreSQL’s generate_series(2, 10, 2) gives you 2, 4, 6, 8, 10. The script uses that same pattern to pick which products get orders.

-- Seller 1 owns products 1 to 1000, seller 2 owns 1001 to 2000, and so on.
INSERT INTO products (id, seller_id, name)
SELECT id, 1 + (id - 1) / 1000, 'Product ' || id
FROM generate_series(1, 1000000) AS product(id);

-- Give each even-numbered product 20 orders: 500,000 products × 20.
INSERT INTO orders (product_id)
SELECT id
FROM generate_series(2, 1000000, 2) AS product(id)
CROSS JOIN generate_series(1, 20) AS copies(n);

-- Give products 1, 5, 9, ... eight subscriptions each.
INSERT INTO subscriptions (product_id)
SELECT id
FROM generate_series(1, 1000000, 4) AS product(id)
CROSS JOIN generate_series(1, 8) AS copies(n);

-- Give three other groups an update, a trial, or a discount.
INSERT INTO subscription_updates (product_id, deleted_at)
SELECT id, NULL FROM generate_series(3, 1000000, 16) AS product(id);

INSERT INTO trial_redemptions (product_id)
SELECT id FROM generate_series(7, 1000000, 16) AS product(id);

-- Alternate active and inactive discounts, starting with active on product 11.
INSERT INTO discount_products (product_id, active)
SELECT id, id % 32 = 11 FROM generate_series(11, 1000000, 16) AS product(id);

-- Refresh the statistics PostgreSQL uses to plan queries.
ANALYZE;

Index each related table’s product_id and the pair (seller_id, id) on products. Use the same data, indexes, database settings and API worker and connection pool sizes for both runs.

Replay the same requests. Save this as reads.js. Each scenario issues one HTTP request per iteration. Both cycle deterministically through sellers and vary the page or detail ID on successive passes.

import http from 'k6/http';
import exec from 'k6/execution';

function scenario(rate, fn) {
  return {
    executor: 'constant-arrival-rate', rate, timeUnit: '1s',
    duration: __ENV.DURATION || '5m', preAllocatedVUs: rate,
    exec: fn,
  };
}
export const options = {
  scenarios: { catalog: scenario(475, 'catalog'), detail: scenario(25, 'detail') },
  thresholds: {
    http_req_failed: ['rate==0'], dropped_iterations: ['count==0'],
    'http_req_duration{scenario:catalog}': ['p(99)>=0'],
    'http_req_duration{scenario:detail}': ['p(99)>=0'],
  },
};
function read(list) {
  const i = exec.scenario.iterationInTest;
  const seller = 1 + i % 1000;
  const base = (seller - 1) * 1000;
  const pass = Math.floor(i / 1000);
  const path = list
    ? `/products?seller_id=${seller}&cursor=${base + (pass % 10) * 100}&limit=100`
    : `/products/${base + 1 + (pass % 1000)}?seller_id=${seller}`;
  http.get(__ENV.BASE + path, { tags: { name: list ? 'catalog' : 'detail' } });
}
export function catalog() { read(true); }
export function detail() { read(false); }

Warm each version for two minutes, then measure for five. Alternate before/after run order across at least three pairs. The permissive latency thresholds expose per-route summaries. They are placeholders for your service’s latency targets. k6 constant arrival rate

BASE=http://api-host:8000 DURATION=2m k6 run reads.js
BASE=http://api-host:8000 k6 run --summary-trend-stats='med,p(95),p(99)' reads.js
MeasurementWhat to record for each run
LatencyPer-route k6 median (P50), P95 and P99. A combined percentile can hide a detail regression.
ThroughputCompleted HTTP requests divided by measured seconds, error rate and dropped iterations. If the generator runs out of virtual users, increase capacity and repeat both variants.
Database CPURun mpstat -P ALL 1 on the dedicated Linux DB host during the measured window. Compare average user and system CPU across all eight vCPUs. Record I/O wait separately.
Buffer hits and readsSnapshot pg_stat_database.blks_hit and blks_read for the benchmark DB before and after the measured window, using separate transactions. Compare deltas per completed request. A shared-buffer miss can still hit the OS cache. Record device reads with iostat -dx 1 to see storage traffic.
Execution plansCapture the actual list and detail SQL from SQLAlchemy. Outside the load run, execute each with the same bound values and EXPLAIN (ANALYZE, BUFFERS). Compare subplan loops, actual rows, shared hits and reads. Verify the child tables disappear from the optimized list plan.

Show the timings from each run. If the catalog’s response time varies as much between runs as it does between versions, it’s too early to say the page got faster. The query plan can still show that the catalog skipped the deletion checks. PostgreSQL 17 guide to EXPLAIN

Enlarged diagram