Handling Time-Variant DAGs with Constraints in Postgres
Vehicle attachments in a fleet (trucks pulling trailers) are modeled as a time-variant DAG in a single Postgres table of edges with validity intervals and a source-authority priority. Deferred constraint triggers run PL/pgSQL checks at commit to reject cycles and overlapping incoming edges per node, so multi-statement batches can proceed before validation. An add_edge() helper resolves conflicts by truncating, splitting or deleting overlapping intervals according to priority. Recursive CTEs with temporal filters then answer point-in-time snapshots and downstream traversal queries; full code is open source.
Related posts
- Simplifying Time-Based Queries with Range Columns
Supabase mediumAdeptPostgres range types such as tstzrange replace separate start_at/end_at columns with a single range value, which makes time-window queries and overlap prevention simpler. The && operator finds overlapping ranges directly, and an exclusion constraint using GiST rejects overlapping reservations at the database level. With the btree_gist extension, the constraint can be scoped per resource, for example `exclude using gist (table_id with =, duration with &&)`. That combination yields an overlap-proof reservations table without application-side checks.
- Debugging deadlocks in Postgres
incident.io mediumAdeptPostgres deadlocks come from transactions acquiring locks in inconsistent orders, and the main fix is to restructure transactions so they always lock resources in the same sequence. Explicit FOR UPDATE or advisory locks, narrower FOR NO KEY UPDATE locks, and jittered retries also work, but they all reduce parallelism. In a real case at incident.io, two seemingly identical bulk upserts in a Catalog sync deadlocked. Postgres acquires row locks one at a time during a multi-row INSERT ... ON CONFLICT, and the rows were randomly ordered after passing through a Go map, so sorting the rows before upserting eliminated the deadlock.
- Postgres as a Graph Database: (Ab)using pgRouting
Supabase mediumAdeptThe pgRouting extension, usually paired with PostGIS for geospatial shortest-path queries, can serve as a lightweight graph layer in Postgres instead of Apache AGE or Neo4j. Three non-GIS examples model graphs as SQL node and edge tables: pgr_dijkstra computes a project's path through a task-dependency DAG, pgr_astar routes data across servers weighted by latency, and Dijkstra paths over a video-relationship graph produce ranked recommendations via ordinary SQL aggregation. Each example includes the table schemas and queries.
- Sequences and other volatiles in Neki
PlanetScale hardMasterNeki, PlanetScale's sharded Postgres, implements Postgres sequences by classifying sequence operations like nextval() as router-only, with an authoritative shard hosting all sequences so values are never duplicated across shards. The planner relies on Postgres's immutable/stable/volatile expression classification: immutable expressions can be pushed to shards, stable ones like now() or to_char() need consistent clocks or GUCs such as lc_time, and volatile ones must run exactly once per row of the table expression. Determining that cardinality correctly under cross-shard joins, filter reordering and shard-local join pushdown is the hard part, because optimizations that deduplicate join-multiplied rows are invalid for volatile expressions.
- Postgres as Your Platform: Building Event-Driven Systems with Schema Changes
Neon mediumAdept
Postgres event triggers, transactional DDL and LISTEN/NOTIFY can turn schema changes into reliable events that drive downstream automation such as SDK generation, warehouse syncs and documentation updates, with no external queue. The pattern uses a ddl_command_end event trigger that writes pg_event_trigger_ddl_commands() metadata to an outbox table and calls pg_notify, all inside the DDL transaction, so events exist exactly when the schema change commits. A Python psycopg2 worker listens for notifications and claims rows from the outbox, which also supports polling fallback, replay and monitoring of backlog. Practical details cover tagging tenant schemas, using a session setting to avoid infinite loops when automation itself runs DDL, connecting directly rather than through a pooler, and keeping Neon listeners from scaling to zero.