Postgres Event Tables as the Instrumentation Substrate API-First Teams Own Outright
A two-layer schema and pre-aggregation keep Postgres analytics fast.

For API-first teams, a well-designed Postgres event table is the instrumentation substrate itself. It gives the team ownership of the schema, query logic, and governed datasets behind funnels, retention, and activation. Teams can keep that ownership as workloads grow if they design durable capture, pre-calculated metrics, and safe analytical access as separate parts of the system.
Why API-first teams already have the raw material for product analytics
A common misconception is that a product analytics platform performs collection work that an API-first team cannot reproduce. The underlying operation is much more familiar than that. Product analytics platforms ingest events, aggregate them, render results, and add capabilities such as session replay or auto-capture. Postgres already performs the ingestion and aggregation steps. For many applications, the starting model is already present in a users table, an events table with user_id, event_name, created_at, and JSONB metadata, and a subscriptions table.
The prerequisite is explicit event logging, regardless of destination. A platform supplies a destination and tools for working with the resulting records. When those records stay in an owned event table, the team controls which events exist, how they are interpreted, and which datasets downstream consumers receive. Teams can own their data from the start, well before they outgrow a vendor.
The two-layer schema that separates durable capture from queryable reporting

The capture layer stores one row per incoming event, including id, user_id, event_name, occurred_at, received_at, and the full original payload as JSONB. The reporting layer has curated tables or materialized views whose columns have been cleaned, typed, and enriched. Dashboards and aggregations read that layer.
The two timestamps provide information that a single timestamp discards. The gap between occurred_at and received_at shows how much source lag there is and helps reveal delivery failures. Raw JSONB serves a different purpose. It preserves the body for audit, replay, and reprocessing when the reporting schema evolves. If the definition of “activated” changes, the team can recompute historical results from the retained payload rather than accepting the limits of an earlier projection.
Juno provides a concrete example of an owned analytics model. Its AnalyticsEvent includes projectId, environment, type, category, subcategory, properties, createdAt, and updatedAt, with types including CLICK, VISIT, INPUT, and CUSTOM. This is an implementation example only. It treats Postgres as the analytics destination from the outset. In the two-layer design, reporting transformations happen before analytical reads, so each dashboard request does not pay to clean and interpret the same events again.
Indexing the event table so time-windowed and tenant-scoped queries stay fast as data grows
A B-tree on timestamps becomes expensive as a time-series event table grows. BRIN, or Block Range Index, has a different way to keep that cost down. It stores the minimum and maximum timestamps for physical block ranges instead of indexing every row, so the planner can skip blocks outside the requested window. Its size can be orders of magnitude smaller than a B-tree on the same column. The fit depends on chronological writes, because block skipping works well when physical storage order correlates with time.
Tenant-scoped reads need an index that complements BRIN. A composite index on (tenant_id, event_name, occurred_at) bounds relevant event scans by tenant, event, and time. Juno uses (projectId, environment, type, createdAt DESC, id DESC) for project-scoped, filtered, time-ordered pagination. Scope comes first in both designs. The later fields match the filters and ordering that consumers need.
Partitioning addresses the remaining growth of the table and its indexes. Monthly or quarterly partitions on occurred_at give each partition its own BRIN index. Old partitions can move to cheaper storage or be archived, while recent-data queries avoid historical blocks. Indexing and partitioning therefore solve different parts of the same problem. One narrows the work inside the relevant data, while the other keeps unrelated history outside that work.
The five core analytics queries the event table already supports
Funnel conversion, retention cohorts, feature adoption, activation, and session analysis are SQL patterns over the event model. A funnel is built from a chain of named common table expressions. A signup CTE establishes the initial cohort, an activation CTE filters that cohort through a time-windowed EXISTS or join, and a paid CTE applies a longer conversion window. Each transition produces a percentage column.
Retention requires equal care with absent activity. date_trunc assigns users to cohorts, while generate_series produces complete week buckets and a LEFT JOIN attaches activity. The zero-fill is essential to an honest matrix. Omitting inactive weeks would hide the very behavior retention analysis is meant to reveal. Feature adoption is simpler, using COUNT(DISTINCT user_id) with an event-name filter and time window, but its result still depends on one consistent definition of that event across the codebase.
Activation and session analysis follow the same basic pattern of a predicate, a time window, and an aggregation. Neither requires a new underlying data model. SQL is a poorer fit when non-technical teammates need to build their own funnels, when they need UI auto-capture, or when the task calls for session replay. Those needs can make a platform the right choice. They concern interaction, collection convenience, and presentation rather than exclusive access to the underlying analytical computation.
Why pre-aggregation into summary tables is not optional as event volume grows
Querying raw events on every dashboard load makes production absorb the same analytical cost repeatedly. Large scans and aggregations compete with application writes for I/O, memory, and locks. The pressure grows with both history and demand. Customer-facing dashboards are particularly demanding because they combine complex aggregates with sub-100ms latency requirements and concurrency that scales with active users. Indexes alone do not remove that competition.
Summary tables and materialized views move computation ahead of consumption. Scheduled rollup jobs suit freshness windows measured in tens of minutes, while incremental workers support sub-minute to low-single-digit minute freshness. Neither approach makes computation disappear. As the underlying volume grows, rollup jobs can themselves contend with OLTP, limiting how much detail the team can afford to pre-calculate. Postgres-only analytics can support datasets up to several terabytes, but that requires planning, oversight, and investment.
This is a maturation step for analytics in Postgres. The architectural requirement is to stop treating every read as an opportunity to reconstruct the answer from raw history. Pre-aggregation also creates a new responsibility. Summary tables encode definitions, so two tables called “MRR” can produce different numbers if their calculation logic differs. Once computation is organized, the next constraint is agreement about what is being computed.
Defining metrics once so every consumer — human or agent — sees the same number
A trustworthy metric needs one documented definition, one calculation source, one owner, and an inspectable changelog. The team must also record when it was last reconciled. These decisions require deliberate work by the team. A pre-calculated result is only dependable when consumers can identify the meaning and authority behind it. Otherwise, moving work out of read-time queries just makes it faster to get answers that disagree.
A data dictionary gives those decisions an operational form. For each metric, it records what is measured, how the calculation works, which table or materialized view produces it, who owns it, and when it was last verified against reality. This provides a reference when numbers diverge. Without it, MRR calculated three different ways across dashboards, SQL queries, and agents leaves no clear basis for recovery when a discrepancy appears.
The same governed summaries make proactive delivery practical. Metrics should be calculated ahead of time and pushed into inboxes, Slack, or the team’s communication layer rather than depending on someone remembering to check. Agents need that same canonical source. If definitions remain outside the data layer, an agent can derive a plausible calculation that differs from the dashboard’s calculation, with neither answer clearly authoritative.
Using Postgres event triggers and the outbox pattern to make schema changes observable
Schema changes are events that can be instrumented too. Postgres event triggers run when DDL commands such as CREATE, ALTER, and DROP execute, inside the same transaction as the change. A trigger failure rolls the schema change back. Because the change and its record are atomic, the database can record schema changes as they happen without waiting for a separate observer to notice them afterward.
The outbox pattern makes those records durable work items. An event trigger writes the command, an object represented as JSONB, and created_at to schema_change_log, then issues a NOTIFY. Workers read the table and mark records complete when they have processed them. After a crash, unfinished records are still there for retry, which gives at-least-once delivery. The notification is the wake-up signal, while the table preserves the work.
Neon illustrates this pattern with FleetOps, a logistics SaaS where adding a sensor type changes IoT device schemas and triggers downstream synchronization. Event triggers and the outbox coordinate TypeScript SDK generation, warehouse synchronization, and dashboard updates without an external message queue. The mechanism remains native to Postgres. Workers that are connected use LISTEN schema_changed, and publishers send NOTIFY on that channel. The resulting records make schema-change frequency, slow automations, and failures queryable through the same event-oriented approach used for application behavior.
What the Postgres-only approach requires before agents start querying it
Governed summaries do not, by themselves, make direct production access safe. Agents can exhaust connection pools, run unbounded aggregations over raw events, or derive calculations that bypass canonical definitions. Their access patterns can be unpredictable. When agents become part of the system, Postgres becomes part of the application’s safety boundary, so controls must work at the data layer without relying entirely on how the application behaves.
Row-level security restricts access to the current user’s tenant regardless of the query an agent constructs. Purpose-specific roles define permitted data access and actions, with the database validating access before execution. Statement logging for the agent’s role provides an audit trail of queries and modifications. These mechanisms need deliberate application.
The architectural prescription is to separate access patterns. Production Postgres should not simultaneously serve every analytical query, agent lookup, and workflow automation. CDC or a governed copy can move analytical truth away from the production workload. Tiger Data proposes a fork-first approach when agent work requires writes, with agents working in isolated forks and results reviewed before merging. A governed analytical copy meets the other need: shared, read-oriented metrics that keep open-ended analytical traffic off production.
Governed Parquet and DuckDB as the analytical copy that agents and humans share safely
Pre-modeled event data becomes Parquet datasets, whose columnar format suits the aggregations behind funnels, retention, and activation. DuckDB reads those files directly with no need for more infrastructure. Canonical definitions are enforced before consumers receive the datasets, so moving the computation does not require surrendering control over its meaning. The owned Postgres records remain the foundation.
Agents discover available datasets and request them by name instead of exploring production schemas or submitting raw SQL against them. Their analytical queries stay off the production instance. That removes agent-driven exhaustion of the production connection pool from this access path. The same datasets can serve dashboards, AI-generated reports, and API responses, giving human and agent consumers a shared calculation source.
MCP provides a common interface for that access. A single MCP server exposes governed datasets, replacing the N×M integration problem with N+M implementations of a shared protocol. The July 28, 2026 MCP specification introduces a stateless core without protocol-level sessions. The access layer can thus run behind a plain round-robin load balancer with no need for sticky sessions or a shared session store. For Supabase teams, putting the governed copy behind that server keeps queries from agents off production Postgres.
This is headless analytics in a concrete form. As with headless CMS, the data and its delivery are independent of any single front end. The governed event-derived datasets supply the content, while MCP or an API supplies access for dashboards, agents, Slack bots, and email reports.



