Franz Kafka's favorite sister
Topic — A named, append-only log of records. Analogous to a
Kafka topic or a database table. Each topic has a backing PostgreSQL
table with a monotonically increasing eid (event id) as its primary
key.
Record — A single entry in a topic, consisting of a key, a
value, optional meta (jsonb), a timestamp, and an eid. Records
are immutable once written.
eid — Event id. A sequence number assigned to each record within a topic, starting at 1. Eids are monotonically increasing within a topic.
Producer — Any caller that appends records to a topic via
append! or append-one!.
Consumer — A long-running process that reads records from
a topic and processes them via a handler function. Managed by
start-consumer.
Consumer group — A named set of consumers sharing the same
offset within a topic. Identified by the :group key in a selection.
Multiple independent groups can read the same topic, each maintaining
its own position. A consumer group has a one-to-one relationship with
the subscription.
Subscription — A record in the subs table that tracks the
current read position (cursor/offset) of a consumer group within a
topic. Created automatically by start-consumer, or explicitly with
ensure-subscription / add-subscription!.
Offset — The eid of the last record successfully processed
by a consumer group, stored in the subscription record. The next
fetch will return records with eid > offset. An offset of 0 means
nothing has been consumed yet.
Lag — The number of records a consumer group has not yet
processed: topic-eid − offset. A lag of 0 means the consumer is
fully caught up.
Serializer / Deserializer — Functions that convert between
Clojure values and the column type stored in PostgreSQL (:bytea,
:text, or :jsonb). Built-in options: :string, :json, :edn.
All of the examples assume the following require:
(require '[ottla.core :as ottla])
The primary API operations take a config, which has at least the following keys:
:schema - The postgres schema for the ottla logs and subscription tables.:conn-map - A map of parameters for connecting to the the DB.Additionally, the administrative operations (create/remove topic, etc)
require a connected config, which is a config like the above that
includes a :conn key for the active database connection.
Unless you need more control, though, the following pattern is the easiest way to start build and use this config. To set up a new ottla system in a database:
(ottla/with-connected-config [config (ottla/make-config {:database "fancy"
:user "bob"
:password "the-password"})]
(ottla/init! config))
Which would connect to the postgres database and create the necessary schema and tables within it.
After ottla has been initialized with the ottla/init! operation,
topics can be created with add-topic!:
(ottla/with-connected-config [config {,,,}]
(ottla/add-topic! config "my-new-topic"))
When creating a topic, you choose the underlying data type of the key
and value columns for the backing store with the :key-type and
:value-type options. The default is binary (bytea column).
Please note that not all columns types will be compatible with every serializer. Below is the compatability chart for the built-in serializers:
| serializer, type | bytea | text | jsonb |
|---|---|---|---|
:edn | [x] | [x] | |
:json | [x] | [x] | [x] |
:string | [x] | [x] |
For production use, ensure-topic is often preferable to add-topic! — it
returns the existing topic if it already exists with the same column types,
or creates it if it doesn't. It throws if the topic exists with different
column types, which guards against accidental schema drift:
(ottla/with-connected-config [config {,,,}]
(ottla/ensure-topic config "my-new-topic" :value-type :jsonb))
To list all existing topics:
(ottla/with-connected-config [config {,,,}]
(ottla/list-topics config))
;; => [{:topic "my-new-topic" :key-type :bytea :value-type :jsonb} ,,,]
After ottla has been initialized with the ottla/init! operation,
topics can be created with remove-topic!:
(ottla/with-connected-config [config {,,,}]
(ottla/remove-topic! config "my-new-topic"))
Note that is a destructive action, and all data from the topic will be removed immediately.
Often, you can retain all messages for a given topic. If there's a
need to prune old records, use trim-topic!. Exactly one mode must be
provided:
;; Delete all records with eid less than 1000
(ottla/trim-topic! config "my-topic" :before-eid 1000)
;; Delete all records older than a given timestamp
(ottla/trim-topic! config "my-topic" :before-timestamp #inst "2024-01-01")
;; Delete all records before the current maximum eid
;; The most recent record is always retained
(ottla/trim-topic! config "my-topic" :all? true)
trim-topic! returns the number of records deleted.
By default, the deletion is clamped to the minimum subscription cursor
across all consumer groups. This prevents deleting records that have
not yet been consumed. Pass :ignore-subscriptions? true to delete
unconditionally:
;; Delete unconditionally, regardless of subscriber position
(ottla/trim-topic! config "my-topic" :all? true :ignore-subscriptions? true)
Only the most recent record will be retained from the above.
To add to a topic's log, call append! with records, which are maps
like the following:
:key - data key:value - data value:meta - A map of optional metadata (analogous to Kafka headers)There are several built-in serializers that can be applied to the key and value. The key and value do not need to be the same column type or use the same serializer.
The built-in serializers can be referenced by keyword instead of a
function. :string, :json, or :edn
When the key are value are stored in binary format, a key and/or value serializer must be provided if the key or value are not already binary data. A serializer is a function that takes a key or value and returns a binary representation that can later be deserialized by consumers. As a simple example, here's an edn serializer and deserializer:
(def charset java.nio.charset.StandardCharsets/UTF_8)
(defn serialize-edn
[obj]
(.getBytes (pr-str obj) charset))
(defn deserialize-edn
[ba]
(with-open [rdr (java.io.PushbackReader.
(java.io.InputStreamReader.
(java.io.ByteArrayInputStream. ba)
charset))]
(clojure.edn/read rdr)))
So, assuming these serializing functions, here's how we might insert edn data into a topic:
(ottla/append! config "my-new-topic"
[{:value {:oh "cool"}} ,,,]
{:serialize-value serialize-edn})
Note that this is already provided as a built-in :edn serializer,
but the above is for demonstration.
To insert a single record, use append-one!:
(ottla/append-one! config "my-new-topic"
{:key "user-123" :value {:event "login"}}
{:serialize-key :string :serialize-value :json})
When topic is a name, each append first looks up the topic's column
types. To skip that query, pass the topic map returned by add-topic!,
ensure-topic, or list-topics instead:
(def events (ottla/ensure-topic config "events" {:key-type :text :value-type :jsonb}))
(ottla/append-one! config events
{:key "user-123" :value {:event "login"}}
{:serialize-value :json})
The map's :key-type and :value-type must match the topic. Topics
can't change after creation, but if one is removed and recreated with
different types, fetch a fresh map.
Appends to a topic are serialized: each topic has a trigger that takes a transaction-scoped advisory lock before any eid is assigned, and the lock is held until the appending transaction commits or rolls back. This guarantees that records become visible in eid order, so a consumer can never advance past a record that is still being written by a slower transaction.
The practical consequences:
Topics created by older versions of ottla get the trigger when init!
is run again.
Consumers asynchronously listen for messages on a topic and run a
handler to deal with them, updating the subscription afterwards.
Consumers are designed to be run in a managed Consumer object, which
can be started like this:
(ottla/start-consumer config {:topic "my-new-topic"} handler {:deserialize-value deserialize-edn})
This will spin up and return a Consumer that should be kept around
until ready to stop with (.close consumer). Consumers will usually be
long-lived and can be managed with whatever component lifecycle
framework you choose, but can also be used with with-open for
short-lived consumers.
If no subscription exists for the given topic and group, one is created
automatically at startup with the cursor set to 0, so the consumer will
read from the beginning of the topic. To start a new group somewhere
else, create its subscription first with ensure-subscription and its
:from option (see Managing subscriptions
explicitly). reset-consumer-offset!
only moves an existing subscription.
;; Graceful shutdown — waits up to await-close-ms for in-flight work to finish
(.close consumer)
;; Or use with-open for short-lived consumers
(with-open [consumer (ottla/start-consumer config {:topic "my-new-topic"} handler opts)]
(Thread/sleep 5000))
By default, a Consumer maintains 2 database connections: one solely for listening for real-time notifications from the database, and one for fetching records, which it also holds its group's lock on (see One active consumer per group). The handler receives this latter connection, and can reuse it. It also runs 3 threads: a listener, a scheduler (for polling), and a worker (for the handler). Consumers on a shared listener, and poll-only consumers, keep just the one connection.
Many consumers in one process can share a single LISTEN connection.
Start a listener with start-listener and pass it to
start-listening-consumer:
(with-open [listener (ottla/start-listener config)]
(let [orders (ottla/start-listening-consumer config listener {:topic "orders"} handle-order)
audit (ottla/start-listening-consumer config listener {:topic "orders" :group "audit"} audit)
emails (ottla/start-listening-consumer config listener {:topic "emails"} send-email)]
,,,))
Close the listener after the consumers that use it. For health
checks, (ottla.protocols/status listener) reports whether it is
:connected?, whether it's :listening?, the :topics it has
consumers for, and its :reconnects. A consumer's status reports :listening?: whether it's
currently getting real-time delivery, or only polling (e.g. while its
listener reconnects). The listener's :conn-map option can point it at
a different server than the config's.
For a poll-only consumer, use start-poll-only-consumer. It uses no LISTEN
connection, and picks up new records every :poll-ms, so lower
:poll-ms to suit the latency you need:
(ottla/start-poll-only-consumer config {:topic "reports"} handler {:poll-ms 1000})
A consumer polls on a ScheduledExecutorService. By default each
consumer creates a single-threaded one, but you can pass your own as
:scheduler, to share it across consumers or to control its threads.
A listener runs as one long-lived task on an ExecutorService,
occupying one of its threads for as long as the listener is open. By
default each listener creates a single-threaded one, but you can pass
your own as :executor. Make sure it has a thread to spare: an
unbounded pool or a virtual-thread executor works, but don't give the
listener a fixed pool sized for other work.
Ottla never shuts down an executor or scheduler you pass in.
(def scheduler (java.util.concurrent.Executors/newScheduledThreadPool 1))
(def listener (ottla/start-listener config {:executor (java.util.concurrent.Executors/newVirtualThreadPerTaskExecutor)}))
(ottla/start-listening-consumer config listener {:topic "orders"} handler
{:scheduler scheduler})
The :group key in the selection map identifies an independent consumer
group. Multiple groups can read the same topic and each maintains its own
offset, so they receive all records independently:
(ottla/start-consumer config {:topic "my-new-topic" :group "indexer"} handler opts)
(ottla/start-consumer config {:topic "my-new-topic" :group "notifier"} handler opts)
A handler is a function of 2 args, the ottla connected config and a
vector of records. It will be called on its own Thread, but will
receive records in order. Each invocation may receive up to :max-records
records at once, so handlers should be written to process a variable-sized
batch rather than assuming a single record.
The options arg accepts the following keys:
:poll-ms - how often to poll the database for new records on the
topic. This is primarily used as a fallback in case of LISTEN/NOTIFY
misses. (default 15000):scheduler - a ScheduledExecutorService to run polling on.
(default: a new single-threaded one):await-close-ms - when closing the Consumer, how long to wait for
all threads to completely finish their work before shutting it down
forcibly.:max-records - maximum number of records to fetch per batch (default 100):conn-map - a connection map for the consumer's own connection, in
place of the config's :conn-map:reconnect-ms - how long to wait before reconnecting after the
consumer's connection breaks. (default 2000):deserialize-key - a deserializer for the record keys:deserialize-value - a deserializer for the record values:exception-handler - a function that will receive any uncaught
Exception object (see below):xform - optional transducer applied to records after deserialization:commit-mode - controls when the consumer offset is advanced:
:auto (default) — commits the offset when the batch is fetched, before calling the handler; a batch whose handler throws is not redelivered:tx-wrap — fetches the batch, runs the handler, and commits the offset in a single transaction; the offset only advances if the handler returns without throwing:manual — never commits automatically; use commit-offset! in your handlerstart-standalone-consumer (and its alias start-consumer) also
accepts these options, which configure the
consumer's own listener (pass them to start-listener for a shared one):
:listen-min-ms - minimum delay between checks of the LISTEN connection
for notifications, used right after activity. (default 10):listen-max-ms - maximum delay between LISTEN checks. While idle, the
delay doubles from :listen-min-ms up to this value, so it bounds the
latency of the first record after a quiet period. (default 250):listen-ms - alias for :listen-max-msIts :conn-map and :reconnect-ms options apply to its listener too.
Uncaught exceptions thrown either in the handler, any deserializer, or
from fetching will be caught and fed to the exception-handler, which
by default just prints the exception, but could instead log it or in
some other way act on it. If the exception-handler returns
ottla/shutdown (i.e. :ottla/shutdown), the Consumer will begin its
shutdown process.
Only one consumer in a group processes records at a time. Each consumer keeps a connection of its own, and only fetches while that connection's session holds a Postgres advisory lock on the group's subscription. Start more consumers in the same group, in the same process or in others, and they wait as hot standbys. On each notification or poll, a standby tries to take the lock. Once the active consumer's session ends, the first standby to try gets the lock and carries on from the group's offset.
A standby takes over:
:poll-msBecause the lock and the fetches share one session, a consumer can't
fetch after losing its lock. A consumer whose connection breaks
reconnects on a later notification or poll, no sooner than
:reconnect-ms after, and comes back as a standby. A consumer's status
reports :active? (whether it holds its group's lock), :connected?,
and :reconnects.
Session advisory locks need a real session, so don't connect consumers through PgBouncer in transaction pooling mode. Session mode, or a direct connection, works.
The handler runs on a single worker thread, one batch at a time. While a batch is in progress, at most one wake-up (from a notification or a poll) waits behind it, and newer ones replace it, so wake-ups coalesce rather than pile up. No records are lost: the next fetch starts from the group's offset. But a slow handler delays every record behind it, so hand long-running work off to a separate thread pool inside the handler.
The guarantee depends on the commit mode:
:auto (default) — at-most-once. The offset is committed when
the batch is fetched, before the handler runs. If the handler throws,
or the process dies while the handler is running, that batch is not
delivered again.:tx-wrap — at-least-once. The offset is committed in the same
transaction as the handler, so if the handler throws (or the process
dies mid-batch) the transaction rolls back and the batch is delivered
again on the next notification or poll. If the handler's side effects
are writes to the same database, made through the connection in the
config passed to the handler, they commit or roll back together
with the offset, giving effectively-once processing.:manual — at-least-once for anything you haven't passed to
commit-offset!.:auto | :tx-wrap | |
|---|---|---|
| Handler throws / process crashes | batch is skipped | batch is retried |
| Record that always fails | skipped; group moves on | blocks the group until fixed or skipped |
| Transaction during handler | none | open for the whole handler, holding a row lock on the group's subscription |
| Same-database writes in handler | independent of the offset | atomic with the offset (effectively-once) |
| External side effects (HTTP, email, …) | at most once | may repeat on retry; make them idempotent |
Use :tx-wrap when every record must be processed, and especially
when the handler's work is writes to the same Postgres database
(projections, read models, moving data between tables). Keep handlers
short: a long-running handler is a long-running transaction, which
holds back vacuum and blocks reset-consumer-offset! for that group.
A record that always makes the handler throw is retried on every
notification or poll, so the exception handler should alert on
repeated failures; move the offset past a bad record with
reset-consumer-offset!.
Use :auto when losing a batch is acceptable (cache invalidation,
metrics, best-effort notifications), or when the handler is slow or
mostly does external I/O and you don't want to hold a transaction
open. Since a batch that throws is gone, handle errors per record
inside the handler (retry, log, or write to a dead-letter topic)
rather than letting them escape.
Use :manual when you need control over exactly when the offset
moves, e.g. committing record by record within a batch, or after
handing work off to another thread. Note that until you commit, each
fetch returns the same records again.
To replay a topic from the beginning or from a specific point, reset the consumer group's offset before starting (or while stopped):
;; Replay everything from the start
(ottla/reset-consumer-offset! config {:topic "my-new-topic" :group "default"} 0)
;; Replay from a specific record id
(ottla/reset-consumer-offset! config {:topic "my-new-topic" :group "default"} 42)
start-consumer creates a subscription automatically if none exists, starting from the
beginning of the topic. To control the starting position before a consumer runs, use
ensure-subscription or add-subscription!.
ensure-subscription is idempotent — it creates the subscription if it doesn't exist and
does nothing if it already does. By default (:from :earliest), a newly created
subscription starts at the beginning of the topic and will receive all existing records:
;; Create a subscription starting from the beginning (default)
(ottla/ensure-subscription config "my-new-topic")
;; Create a subscription starting from the current end (skip existing records)
(ottla/ensure-subscription config {:topic "my-new-topic" :group "processor"} :from :latest)
;; Create a subscription starting from a specific eid
(ottla/ensure-subscription config {:topic "my-new-topic" :group "processor"} :from 42)
add-subscription! is the strict variant — it throws if a subscription already exists:
(ottla/add-subscription! config {:topic "my-new-topic" :group "new-group"} :from :latest)
;; => true
(ottla/add-subscription! config {:topic "my-new-topic" :group "new-group"} :from :latest)
;; => throws: Subscription already exists
The :from option only applies at creation time. :latest is useful when you want a new
consumer group to process only future records, ignoring the existing backlog.
list-subscriptions returns all consumer group offsets along with the current max eid and calculated lag for each:
(ottla/with-connected-config [config {,,,}]
(ottla/list-subscriptions config))
;; => [{:topic "my-new-topic" :group "default"
;; :offset 42 :topic-eid 50 :lag 8
;; :updated-at #inst "2024-01-01T12:00:05Z"
;; :timestamp #inst "2024-01-01T12:00:00Z"
;; :topic-timestamp #inst "2024-01-01T12:05:00Z"
;; :timestamp-lag #object[java.time.Duration "PT5M"]
;; :processing-delay #object[java.time.Duration "PT5S"]} ,,,]
:lag is the latest eid minus the offset: an upper bound on the
number of unread records, since eids can have gaps (e.g. from
rolled-back appends). 0 means fully caught up:updated-at is the java.time.Instant when the consumer last committed its offset; nil if the subscription has never consumed a record:timestamp-lag is a java.time.Duration between the last consumed record and the latest record; nil if the topic is empty or :offset is 0:processing-delay is a java.time.Duration from when the last consumed record was published to when the consumer committed it; nil if :updated-at or :timestamp is niltopic-subscriptions returns the same information grouped by topic.
Every topic appears in the result, even those with no subscribers:
(ottla/with-connected-config [config {,,,}]
(ottla/topic-subscriptions config))
;; => [{:topic "my-new-topic"
;; :subscriptions [{:group "default"
;; :offset 42 :topic-eid 50 :lag 8
;; :updated-at #inst "2024-01-01T12:00:05Z"
;; :timestamp #inst "2024-01-01T12:00:00Z"
;; :topic-timestamp #inst "2024-01-01T12:05:00Z"
;; :timestamp-lag #object[java.time.Duration "PT5M"]
;; :processing-delay #object[java.time.Duration "PT5S"]}]}
;; {:topic "unused-topic"
;; :subscriptions []} ,,,]
The subscription maps inside :subscriptions carry the same keys as
list-subscriptions entries, minus :topic (which is on the outer
map).
Prefer one append! with many records over many append-one! calls.
Each call is one INSERT in one transaction, and the costs that limit
producer throughput are paid per transaction, not per record:
;; Slower: one transaction, lock, and NOTIFY per record
(doseq [e events]
(ottla/append-one! config "events" e {:serialize-value :json}))
;; Faster: one of each for the whole batch
(ottla/append! config "events" events {:serialize-value :json})
Without a :conn, every append opens and closes a new connection. For
a long-lived producer, put a pg2 pool in the config, and pass a topic
map rather than a name to skip the topic lookup on each append:
(require '[pg.core :as pg])
(def config
(let [config (ottla/make-config conn-map)]
(assoc config :conn (pg/pool (:conn-map config)))))
(def events (ottla/ensure-topic config "events" {:key-type :text :value-type :jsonb}))
(ottla/append! config events records {:serialize-value :json})
;; on shutdown
(.close (:conn config))
A consumer opens its own connection from the config's :conn-map (or
its :conn-map option), and keeps it until it closes. It holds its
group's lock on that connection (see One active consumer per
group), and fetches and runs its
handler on it. The handler receives that connection in its config,
so use it rather than opening another.
Consumers ignore the config's :conn. You can put a pool in :conn
for producers (see Keep a connection (or pool) in the producer's
config) and pass
the same config to consumers.
A standalone consumer (start-consumer) opens a LISTEN connection of
its own as well. With more than one consumer in a process, start one
listener and pass it to start-listening-consumer instead (see
Sharing listeners and schedulers).
Only one LISTEN connection is needed however many topics and groups
you consume.
To budget connections against the server's max_connections, count:
Leave room for everything else that connects. For example, ten standalone consumers use 20 connections, while ten listening consumers sharing one listener use 11.
With :tx-wrap, the handler runs inside the fetch transaction, so
keep handlers short: a long-running transaction holds back vacuum.
Run each group's consumer in more than one process. One is active and the rest wait as standbys. When the active consumer's process stops, or its connection drops, a standby takes over (see One active consumer per group).
Can you improve this documentation?Edit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |