Trending

World technology news

→
Designing event identities and timelines with PostgreSQL 18 UUIDv7
Software Engineering · 2025
Software Engineering2025

Designing event identities and timelines with PostgreSQL 18 UUIDv7

PostgreSQL 18 introduced built-in UUIDv7 generation in September 2025. A fulfillment event table shows how to separate identity, business time, ingestion time, and duplicate handling.

Archive retrospective · Topic year 2025

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. Separate the information a single event carries
  2. Know which time the UUID can describe
  3. Give retries a separate key
  4. Use explicit ordering when event timestamps tie
  5. Compare a limited deployment with the existing workload
  6. Decide what operators and clients should expect

Separate the information a single event carries

A dispatch scanner watches a parcel move from sorting to a vehicle. While offline, it stores events and uploads them three hours later. A carrier service may also retry an HTTP request after a timeout. The database identity, the time the parcel moved, and the identifier the carrier uses for retry handling each answer a different question. Giving them different fields lets support staff explain what happened without guessing from the order in which rows appear. PostgreSQL 18 was released on September 25, 2025. It added uuidv7() as a built-in generator for time-ordered identifiers. An application can delegate key generation to the server while keeping a consistent contract across several data producers. This retrospective uses a single fictional fulfillment workflow to show what the version change gives the application.

Know which time the UUID can describe

RFC 9562 specifies a leading 48-bit Unix timestamp in milliseconds for UUIDv7. The format also holds version and variant fields and additional bits supplied by its generator. PostgreSQL combines a millisecond timestamp, sub-millisecond information, and randomness. The identifier therefore carries a time-oriented prefix. Multiple producers, clocks, and arrival times create several legitimate meanings of order even when every producer generates conforming identifiers. Use occurred_at for when the business event happened and ingested_at for when the insert recorded it. The timestamp encoded in the UUID can help diagnose when an identifier was generated. A customer timeline follows occurred_at, while an ingestion dashboard can compare the two explicit timestamps. Establish how producers report local time and check clock drift separately. When event time is unknown, represent that situation in the ingest contract so downstream reporting can handle it consistently.

Database access flowConceptual sketch · summary of the article's technical flow

Give retries a separate key

In this example, the carrier uses a stable event reference within each tenant. A unique constraint on tenant_id and external_event_id enforces that rule. The first insert returns the generated identifier and times. A duplicate insert returns no row. The application can then retrieve the existing record if it needs the identifier, or acknowledge that it processed the event earlier. Include a carrier identifier in the uniqueness rule if carriers reuse reference values in separate namespaces. The clock_timestamp() default reads the current time during insertion. A transaction can also use a timestamp fixed at transaction start when that semantics fits the workload. Here the database records ingestion while the producer supplies the business timestamp. Validate incoming timestamps separately to handle missing values or large clock discrepancies. The same retry reference can arrive with different content. A carrier may use different references for dispatch and delivery. When a provider deliberately keeps a reference for corrections, compare the new payload with the stored record and flag differences according to the contract. Define which outcomes count as processing a retry. The recorded ingestion time is an observation made during the insert. If commit time matters for an operational question, measure commit separately in the transaction pipeline.

CREATE TABLE fulfillment_event (
    id uuid PRIMARY KEY DEFAULT uuidv7(),
    tenant_id bigint NOT NULL,
    external_event_id text NOT NULL,
    occurred_at timestamptz NOT NULL,
    ingested_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    event_type text NOT NULL,
    UNIQUE (tenant_id, external_event_id)
);

CREATE INDEX fulfillment_event_timeline
    ON fulfillment_event (tenant_id, occurred_at DESC, id DESC);

INSERT INTO fulfillment_event (tenant_id, external_event_id, occurred_at, event_type)
VALUES (42, 'parcel-194-dispatched', '2025-09-25 09:15:00+00', 'dispatched')
ON CONFLICT (tenant_id, external_event_id) DO NOTHING
RETURNING id, occurred_at, ingested_at;

Use explicit ordering when event timestamps tie

An operator asks for the twenty latest movements for a tenant. The timeline index puts the tenant first, then the business time and identifier. The UUID breaks ties when several events have the same occurred_at. The next-page statement receives the final pair from the previous page and uses a strict row comparison. Every page follows the same order and can continue without counting an ever larger OFFSET. A late upload can add a historical event while a user browses. Live operational views can accept such changes. A reporting export may need a snapshot or a cutoff fixed when the export begins. Decide what the timeline promises before choosing a pagination contract. Verify that a retry and two events at the same timestamp interact correctly with the next-page boundary.

SELECT id, occurred_at, event_type FROM fulfillment_event
WHERE tenant_id = 42
ORDER BY occurred_at DESC, id DESC
LIMIT 20;

PREPARE next_fulfillment_page (bigint, timestamptz, uuid) AS
SELECT id, occurred_at, event_type FROM fulfillment_event
WHERE tenant_id = $1 AND (occurred_at, id) < ($2, $3)
ORDER BY occurred_at DESC, id DESC
LIMIT 20;

Compare a limited deployment with the existing workload

Change the default for new records on a staging copy and preserve existing identifiers. That protects the references held by external systems and foreign keys. The uuid type accepts old version 4 and new version 7 values in the same column. The version extraction function helps inspect a mixed dataset. Timestamp extraction can return null for a version other than 1 or 7. Use it for diagnostics while retaining the original business timestamp. A time-oriented prefix can improve insertion locality in a B-tree, depending on how the database receives writes. Compare equal datasets and concurrency levels before assuming a gain. Measure insert latency, index size, and buffers for the timeline query. EXPLAIN ANALYZE executes its statement. Use an isolated database for meaningful write tests and label any synthetic results as such.

SELECT id,
       uuid_extract_version(id) AS uuid_version,
       uuid_extract_timestamp(id) AS encoded_at,
       occurred_at, ingested_at
FROM fulfillment_event
WHERE tenant_id = 42
ORDER BY occurred_at DESC, id DESC
LIMIT 20;

Decide what operators and clients should expect

Test four cases with operations staff. Retry an event, upload an event late, submit several events at the same time, and read a response containing both identifier versions. Record the expected outcome for storage, API clients, and the timeline. A support engineer should be able to tell from the explicit timestamps whether a delay occurred before upload or during ingest. UUIDv7 values expose some generation time information when used in public URLs. Keep normal authorization checks on every lookup. If a customer asks where a record belongs in the timeline, use the business timestamp and the documented tie-breaker. Preserving old identifiers allows the team to improve the event model without simultaneously changing every reference held outside the database.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.