partition

package
v0.18.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package partition keeps the range partitions of Postgres tables by time: it creates the partitions of the current period and of the next ones ahead, and drops the partitions older than the retention.

A table partitioned by range of a time column has no place for a row of a period without a partition: with no default partition the insert fails. So the partitions are made ahead, and an old period goes as a whole — a DROP of its partition, without the DELETE, the bloat and the VACUUM.

Usage

The migration creates the partitioned table alone; its primary key holds the partition key:

CREATE TABLE messages (
    id         uuid NOT NULL,
    created_at timestamptz NOT NULL,
    PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);

The partitions come from Maintain, run by a worker.Loop on every replica: the first tick at the start, then every hour. Maintain is a worker.TickFunc as it is:

keeper, err := partition.New(log, db, partition.Config{
    Tables:    []string{"messages", "deliveries"},
    Period:    partition.Month,
    Retention: 90 * 24 * time.Hour,
})
if err != nil {
    return err
}
group.Add(worker.NewLoop(log, worker.LoopConfig{
    Name:               "partitions",
    Interval:           time.Hour,
    ImmediateFirstTick: true,
    Metrics:            d.Metrics,
}, keeper.Maintain))

A test calls Maintain itself, with the clock of WithNow, before it writes rows; a run at a later time shows the next periods and the drops.

Partitions

A partition is named after its table and period, in the schema of the table: messages_2026_11 for Month, messages_2026_11_05 for Day. Its bounds are the starts of the periods in UTC, and a column of timestamptz, timestamp or date takes them. A partition of another name is neither counted nor dropped; one whose range overlaps a new partition fails the run, as does a default partition with rows of the new period.

Maintain creates the partitions of the current period and of Ahead periods after it that are missing, table by table in the order of Config.Tables. It drops a partition once its end is Retention old, so no row younger than Retention goes; the tables go in the reverse order, a partition is detached and then dropped. A table that references another by a foreign key is listed after it: its rows go first.

Replicas and locks

A run is one transaction. It takes a transaction-level advisory lock, one for every Keeper of the database, so the runs of the replicas take their turns: the second one finds nothing to do. Then each DDL statement waits for the lock of its table no longer than 10s (lock_timeout): a statement waiting behind a long query would hold every insert into the table behind itself. On the timeout the run fails, and the next tick does the work.

Alerts

The package has no metrics of its own: the Loop records its ticks. Alert when the last success of the Loop is older than a part of the time Ahead leaves before inserts fail — a day for Month:

time() - max without(pod, instance) (
    skit_worker_last_success_timestamp_seconds{worker="partitions"}
) > 86400

Options

  • Config: Tables, Period (Day or Month), Ahead (default 1), Retention (0 keeps every partition).
  • WithNow: the clock of the Keeper (tests); time.Now by default.
Example

A Loop runs Maintain on every replica: at the start and then every hour. The journal keeps 90 days, and the partitions of the next month are always there. The example needs Postgres, so go test builds it but does not run it.

package main

import (
	"context"
	"log/slog"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/assanoff/skit/dbx/pg"
	"github.com/assanoff/skit/partition"
	"github.com/assanoff/skit/worker"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	log := slog.Default()
	db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
	if err != nil {
		log.ErrorContext(ctx, "open", "err", err)
		return
	}
	defer func() { _ = db.Close() }()

	keeper, err := partition.New(log, db, partition.Config{
		Tables:    []string{"messages", "deliveries"},
		Period:    partition.Month,
		Retention: 90 * 24 * time.Hour,
	})
	if err != nil {
		log.ErrorContext(ctx, "partitions", "err", err)
		return
	}
	g := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
	g.Add(worker.NewLoop(log, worker.LoopConfig{
		Name:               "partitions",
		Interval:           time.Hour,
		ImmediateFirstTick: true,
	}, keeper.Maintain))
	if err := g.Run(ctx); err != nil {
		log.ErrorContext(ctx, "group stopped", "err", err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Tables are partitioned by range of a time column, all by the same
	// Period: plain lowercase names, with a schema or without (messages,
	// audit.log). Their partitions are created in this order and dropped in
	// reverse, so a table that references another goes after it.
	Tables []string
	// Period is the range of one partition: Day or Month.
	Period Period
	// Ahead is how many periods after the current one have their partitions
	// (default 1).
	Ahead int
	// Retention is how long rows are kept: a partition is dropped once its
	// end is that old, so no row younger than Retention is. 0 keeps every
	// partition.
	Retention time.Duration
}

Config says which tables a Keeper maintains and how.

type Keeper

type Keeper struct {
	// contains filtered or unexported fields
}

Keeper creates the partitions of its tables ahead and drops the expired ones. It is safe for concurrent use: the runs of all Keepers of a database, on every replica, take their turns.

func New

func New(log *slog.Logger, db *dbx.DB, cfg Config, opts ...Option) (*Keeper, error)

New builds a Keeper of the tables of cfg over db. It checks cfg and does not touch the database: the first Maintain creates the partitions. log may be nil.

Example (Days)

Day partitions with a week of rows, for a log of many rows a day; two days ahead leave a weekend to fix a failing run.

package main

import (
	"context"
	"log/slog"
	"time"

	"github.com/assanoff/skit/dbx/pg"
	"github.com/assanoff/skit/partition"
)

func main() {
	log := slog.Default()
	db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
	if err != nil {
		return
	}
	defer func() { _ = db.Close() }()

	keeper, err := partition.New(log, db, partition.Config{
		Tables:    []string{"audit.log"},
		Period:    partition.Day,
		Ahead:     2,
		Retention: 7 * 24 * time.Hour,
	})
	if err != nil {
		return
	}
	_ = keeper.Maintain(context.Background())
}

func (*Keeper) Maintain

func (k *Keeper) Maintain(ctx context.Context) error

Maintain creates the missing partitions of the current period and of Ahead periods after it, and drops the partitions whose end is Retention old, in one transaction. A second run changes nothing. Maintain waits for the run of another Keeper of the database to end, and its own statements wait for the lock of a table no longer than 10s.

type Option

type Option func(*Keeper)

Option configures a Keeper.

func WithNow

func WithNow(now func() time.Time) Option

WithNow sets the clock of the Keeper (tests); time.Now by default.

type Period

type Period int

Period is the range of time one partition holds.

const (
	// Day is a partition per calendar day in UTC, such as messages_2026_11_05.
	Day Period = iota + 1
	// Month is a partition per calendar month in UTC, such as messages_2026_11.
	Month
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL