← writingmaclulich.com

PostgreSQL read tables for filtering: layout, joins and index cost (Part 2)

Five changes to make when you split, join and index PostgreSQL read tables

  1. Split read tables by what changes togetherBase profile, messaging, commerce and custom fields became separate tables, and later refresh paths could ask for base and commerce work without messaging work
  2. Check who the join drops after a table splitAdding a commerce table needed a fix in August 2021: inner joins became left joins, so a contact with no commerce row could still match an OR
  3. Match each index to the operator you filter withOur “all events” and “any event” filters used array containment and overlap. A GIN index can support both, while a B-tree suits equality, ranges and ordering
  4. Don’t assume a small update means a small index bill273 GB of indexes around 53 GB of base-profile data. An update that can’t stay HOT costs index maintenance even when few columns changed
  5. Check the replica before dropping an indexOne 21 GB index had 87 recorded scans on the writer and 406,420 on the read replica, so the review kept it
The numbers come from Audience Republic’s July 2026 index reviews and its August 2021 commerce work.

Layout and indexes decide what every write costs

This part is for you if you’re laying out PostgreSQL read tables for filtering and want to know what the layout and the indexes will cost you later. It follows the tables at Audience Republic, through a join mistake and indexes that grew larger than the tables they served.

Part 2 of Filtering at scale: how AR’s PostgreSQL design evolved.

The materialized tables made audience filtering practical at Audience Republic, but they also became some of the most expensive data we maintained. By July 2026, one recorded snapshot had 273 GB of indexes around 53 GB of base-profile table data. The messaging table had a different snapshot that month: 830 GB of indexes around 206 GB of data.

Those numbers are where this story eventually arrived. The choices that got us there were much smaller: where to put a field, how to represent a fan’s purchase history, and which index would make the next filter useful. Each choice affected the work we had to do when the underlying data changed.

Part 1 covered why we kept normalised source records and maintained a separate representation for filtering. Here I want to follow the layout of that representation, including a fairly ordinary join mistake that shows how closely the storage and filtering semantics were connected.

Split read tables by what changes together

The filter menu put profile details, messaging activity and purchases next to one another. That was convenient for the person building an audience, but those fields did not come from one source record or change for the same reasons.

Our read-table family came to include base-profile, messaging, commerce and custom-field data. These were ordinary tables maintained by our code, not native PostgreSQL materialized views. The grouping gave us separate places to keep derived data, although separating the tables did not automatically make every refresh selective.

01 / Read layoutOne filter, several kinds of data
Profile details AND / OR purchases AND / OR messaging activity
Shared identity fan + promoter/account
MFPABase profile

Profile fields and memberships

MFPAMMessaging

Activity and subscription data

MFPACCommerce

Purchase and revenue totals

MFPACFCustom fields

Additional audience fields

Conceptual read-table family as the design evolved. A filter uses the fields and joins it needs, not necessarily every table shown.

Commerce is a useful point in the history because we can see the boundary being introduced. The August 2021 work added commerce materialization and changed the filtering code around it. Later refresh paths could request base and commerce work without also asking for messaging work.

That distinction matters under load. A purchase should not inherently require us to rebuild unrelated messaging aggregates. But the table boundary only creates the opportunity to avoid that work. The application still has to choose the right update path, so check that each refresh asks only for the tables it needs.

Check who the join drops after a table split

One of the follow-up fixes in August 2021 changed inner joins to left joins in tag and message-list filtering paths involving the new commerce table.

Consider a simplified filter: people in Sydney OR people who have spent more than $100. Someone in Sydney should qualify even if they have no corresponding commerce row. An inner join can remove them before the WHERE condition is evaluated.

02 / Filter correctnessWhere did the Sydney contact go?
City is Sydney OR total spend > $100
Example contactCity: SydneyCommerce row: absent

INNER JOIN

Requires a matching commerce row
Contact removedThe city condition never gets a chance to match.

LEFT JOIN

Keeps the profile without a commerce row
Contact includedThe Sydney condition is true, so the OR matches.
Invented example explaining the join fix. Missing commerce values still need explicit semantics for other predicates.
-- Before: no commerce row means the contact disappears at the join.
SELECT p.fan_id
FROM profile_read AS p
JOIN commerce_read AS c
  ON c.fan_id = p.fan_id AND c.account_id = p.account_id
WHERE p.account_id = 42
  AND (p.city = 'Sydney' OR c.total_spend > 100);
-- After: retain the profile so the city condition can still match.
SELECT p.fan_id
FROM profile_read AS p
LEFT JOIN commerce_read AS c
  ON c.fan_id = p.fan_id AND c.account_id = p.account_id
WHERE p.account_id = 42
  AND (p.city = 'Sydney' OR c.total_spend > 100);

Simplified explanatory SQL with invented names and values. The historical fix changed the generated joins. This is not a captured production query.

The left join does not settle every missing-data question. We still have to decide whether an absent value means zero, unknown or not yet materialized, especially for negative conditions. It does preserve the possibility that another part of an OR expression can match.

This is why I would trace a layout change all the way back to the filter controls. A faster query that quietly changes the audience is not the optimisation we were trying to make.

Match each index to the operator you filter with

Some audience questions naturally involved sets. A fan might have bought tickets to several events, and the filter could ask for people who bought tickets to all of the selected events or any of them.

The older filtering code already expressed that distinction using PostgreSQL array operators:

-- All selected events must occur in the stored set.
event_ids @> ARRAY[101, 202]
-- At least one selected event must occur in the stored set.
event_ids && ARRAY[101, 202]

Invented event IDs. These illustrate the operators selected by the legacy filter implementation.

A B-tree is useful for scalar equality, ranges and ordering. A GIN index can support array containment and overlap, which made it relevant to this representation. The operator and index operator class have to agree, and having an index on a column is not enough to establish that it helps the query. PostgreSQL index types describes those distinctions.

There were two different combinations to preserve: the set operation inside one event filter, and the AND or OR connecting that filter to other conditions. The interface made them look uncomplicated. The generated SQL still had to preserve both.

Don’t assume a small update means a small index bill

The July measurements make the accumulated cost visible:

03 / Recorded storageThe indexes were larger than the rows
Table dataIndexes
Base profile28 July 2026 · 31 indexes
53 GB table data + 273 GB indexes 326 GB total
Messaging1 July 2026 · 38 indexes
206 GB table data + 830 GB indexes 1036 GB total
Bars share the same scale. Separate dated snapshots, not a before-and-after benchmark or a target index-to-table ratio.

Separate dated snapshots, not a before-and-after comparison. Heap means the table’s main row storage.

There is no useful universal rule that indexes must be smaller than the table. What mattered was whether those indexes were earning their maintenance cost in our workload.

An update creates a new row version. PostgreSQL’s HOT optimisation can avoid new entries in ordinary indexes when the update does not change indexed columns and there is enough room on the existing heap page.

If those conditions do not hold, updating a small part of a wide row can still have a much wider maintenance cost. PostgreSQL HOT documentation explains the conditions.

That is an important limit on the phrase “we only rebuilt a few columns”. It describes the application’s computation, not a guarantee about how little work the database performed. We needed to inspect the columns that actually changed and the indexes attached to them.

Check the replica before dropping an index

The messaging index review contains an example I would keep in any discussion about deleting unused indexes. One 21 GB index had only 87 recorded scans on the writer, but 406,420 on the read replica. The review retained it.

Same indexRecorded scans
Writer87
Read replica406,420

Counts recorded in the July 2026 review, not query rates or a controlled observation interval.

Looking only at the writer would have given us a very misleading picture of its usefulness. The reverse matters too: an index that appears quiet on a replica may enforce uniqueness on the writer.

Scan counts were one piece of the decision. We also needed to understand the observation window, constraints, query shapes and infrequent operations that still mattered. A low number was a reason to investigate, not a deletion instruction.

The later base-table migration records five index removals, whose proposal listed approximately 37 GB of index data. That records a specific cleanup, not proof of a measured latency improvement or a smaller provisioned RDS volume. The useful outcome was a more deliberate index set, with evidence for what stayed as well as what went.

Read the plan before you add a covering index

We also investigated indexes that helped the queries rebuilding these tables, not just the filters reading them. Those are different access paths: one serves the audience question, the other aggregates source records to maintain the answer.

A covering index can carry the values a query needs, but an index-only plan does not guarantee that PostgreSQL avoids every heap visit. Visibility checks can still require heap access when a page is not marked all-visible. That qualification matters on frequently updated data. PostgreSQL index-only scans explains why.

I liked using the RDS database-load view alongside the SQL because it helped narrow down where to investigate. I would still want the query plan and buffer information before deciding whether the problem was the access path, repeated execution or maintenance around those writes. A large I/O band is a useful starting point, not a diagnosis by itself.

Change the layout and the refresh code together

I would keep the distinction between source records and read tables. It let us preserve the underlying data while building a representation suited to audience questions. What needed ongoing scrutiny was the cost and correctness of maintaining that representation as the product grew.

The commerce join fix and the replica index check are small examples of the same problem: a local change has consequences outside the code or database node immediately in front of you. The filter semantics, the write path and the read workload all belong in the decision.

How far to trust it

These are records from one system, not controlled tests

  1. The sizes are dated snapshotsThe index figures are separate snapshots of different tables, not a before and after. The 37 GB from five removals is a proposal’s figure, not a measured latency or volume saving
  2. The scan counts are not ratesThe 87 and 406,420 were counts recorded in the July 2026 review, not query rates or a controlled observation interval
  3. A left join doesn’t settle missing dataWe still have to decide whether an absent value means zero, unknown or not yet materialized, especially for negative conditions
  4. A big I/O band is a place to startIt isn’t a diagnosis. I would still want the query plan and buffer information first
  5. The SQL is simplifiedThe join and event ID examples use invented names and values, not captured production queries

Copy this review checklist

Paste it into a review for any set of PostgreSQL read tables behind a filter.

Read-table review for filters

[ ] Tables are split by what changes together, and each refresh path
    asks only for the tables it needs
[ ] A join to a split table is a LEFT JOIN when the row may be missing
[ ] Absent values have a decision: zero, unknown or not yet materialized
[ ] Each array filter pairs its operator with a matching index
    (GIN can support @> and &&)
[ ] For every index, size and write cost are counted, and a changed
    column is checked for whether the update can stay HOT
[ ] Scans are counted on the writer and the read replica before any
    index is dropped
[ ] The query plan and buffers are read before a covering index is added

The join shapes are the SQL under Check who the join drops after a table split, and the array operators are under Match each index to the operator you filter with.

How I put this together

I rebuilt this from commits, storage snapshots and index reviews, then checked the PostgreSQL documentation

  1. Read the commit historyThe August 2021 commerce work and its follow-up join fixes
  2. Take the dated storage snapshotsBase profile on 28 July 2026, messaging on 1 July 2026
  3. Compare scans on the writer and the replicaThe July 2026 messaging index review
  4. Check each behaviour in the docsIndex types, HOT updates and index-only scans

The next part follows the update path itself: how we worked out which columns needed rebuilding, grouped that work, and tried to keep it correct when several workers reached the same fans.