Skip to content

In development. Expect rough edges and changes. The source code is not public yet.

DBOS 5 min read Deep dive mediumAdept

Postgres SELECT DISTINCT Does Not Scale

Postgres SELECT DISTINCT always scans every index entry matching its predicates, so its cost grows with total matching rows rather than with the number of distinct values. In DBOS's Postgres-backed partitioned queue, finding active partitions took seconds on 'narrow but deep' queues, even with a matching partial index. Postgres has no loose index scan like MySQL's, and the Postgres 18 skip scan doesn't help here. The workaround is a recursive CTE that repeatedly selects min(key) greater than the previous key, giving O(distinct values) cost and a flat ~1 ms latency up to 1M rows per partition.

Related posts

  • PostgreSQL Stories: From slow query to fast—via stats

    Render mediumAdept

    A simple LIMIT 1 join between a ~100k-row postgres_dbs table and a ~90M-row events table ran for hours. The cause was a merge join that scanned ~79M non-matching events sorted ahead of the 'dpg-' serviceId prefix. Adding manual lower and upper bounds on the indexed JSON expression brought the query down to milliseconds, but the real fault was that PostgreSQL only kept statistics on whole JSON objects, not on data->>'serviceId'. Running CREATE STATISTICS on that expression gave the planner accurate distributions, and the original query then finished in under a millisecond without rewrites.

  • You should shard your database

    PgDog mediumAdept

    Sharding Postgres early avoids the operational pain of large single instances, illustrated by an outage where stale planner statistics caused a 300 GB table to be sequentially scanned. Attempts to fix it by raising default_statistics_target added planning time (0.2ms to ~1ms per query, significant at 100k QPS), while making autovacuum analyze more often increased IOPS. Splitting the table into 12 shards cuts writes, autovacuum work and scanned rows by 12x, making migrations like ALTER COLUMN TYPE BIGINT finish in seconds and lowering the cost of mistakes.

  • Dynamic Table Partitioning in Postgres

    Supabase mediumAdept

    Postgres range partitioning can be retrofitted onto an existing "large table" (here, 500 million chat messages) without blocking queries by creating standalone daily child tables, bulk-loading them, adding a CHECK constraint that matches the partition range, and only then running ATTACH PARTITION so Postgres skips the validation scan and its blocking lock. The walkthrough builds a simulated chat app with pl/pgSQL functions that create partitions dynamically. It also covers why large tables hurt (btree depth, vacuum, archiving), the requirement that the partition key be part of composite primary and foreign keys, and ORM support gaps such as Django's lack of composite keys.

  • Implementing "seen by" functionality with Postgres

    Supabase mediumAdept

    Four ways to track post views in Postgres are benchmarked: a naive counter column, an hstore of viewer IDs per post, an association table, and the HyperLogLog extension. HyperLogLog is the recommended default because its tradeoffs are good and it adds no large architectural liabilities. hstore is fine for a quick prototype and performed best with integer IDs. The benchmark uses synthetic users and posts with an 80/20 poster skew, replayed through autocannon with a 10/60/30 mix of list-viewers, read-count and record-view requests.

  • Primary keys in sharded databases

    PgDog mediumAdept

    PgDog generates globally unique primary keys across Postgres shards without extensions or external ID services. It reuses Postgres's hash-partition algorithm, so each shard can call satisfies_hash_partition and loop nextval until a value belongs to that shard. Setting pgdog.next_id_seq as the column DEFAULT is enough, and pgdog.next_uuid_auto does the same for UUIDs. Sequence caching (ALTER SEQUENCE ... CACHE 1000) makes the brute-force loop cheap and cuts WAL writes, at the cost of gaps after a crash but never duplicates.

The quest for software engineering knowledge.

Look:
Layout: