Video in progress

For an event or transaction table that collects billions of rows a year, how do you design the Hibernate entity and the database?

I partition the table by time, add the partition key to the primary key, and make the entity light for writing and often immutable. Old partitions are dropped or archived; reads mostly use projections and a time range.

📖 Answer

A table like this doesn't need most of Hibernate's usual features: records don't change, associations are minimal, reads are by range. I design with that in mind.

The database side. PostgreSQL declarative partitioning, monthly partitions:

create table payment_event (
    id          bigint      not null,
    created_at  timestamptz not null,
    account_id  bigint      not null,
    payload     jsonb,
    primary key (id, created_at)          -- the partition key must be in the PK
) partition by range (created_at);

You need a job that creates partitions ahead of time (or pg_partman). detach and drop of an old partition takes seconds, while deleting a billion rows with DELETE takes days.

The entity side:

@Entity
@Immutable
@IdClass(PaymentEventId.class)
class PaymentEvent {
    @Id Long id;
    @Id Instant createdAt;
    Long accountId;                      // not a @ManyToOne: just the ID
    @JdbcTypeCode(SqlTypes.JSON) String payload;
}

@Immutable turns off dirty checking and UPDATE. There is no @ManyToOne, because FKs and lazy proxies from a partitioned table to big tables are unnecessary load.

Writes: batching (pooled sequence) or straight COPY/JDBC batch. Reads: always with a created_at range, otherwise the planner looks at all the partitions. I make that a required parameter in the repository methods.

Because of the composite PK, find(id) no longer works with a single ID: this is the usual trade-off. If external systems refer to rows by id alone, a separate small index table or encoding the time into the ID (UUIDv7, Snowflake) helps.