In the previous article, I showed how I recorded Linux box/app metrics natively without the usual Prometheus, Grafana combo. Here a high I/O usage metric led me to Lance queries that were not using their indexes properly.
The focus here is the queueing layer that produces the work, and the place where Fennel shines. Redis holds the specialized job queues. The whole server-side protocol — push, claim, bookkeeping — fits in one file, compiles to plain Lua, and is tested against a real Redis, easily instrumented by devenv.sh.
The index miss and its EXPLAIN ANALYZE guards are the other half: the part that keeps the queries behind the queue honest. The I/O is barely visible now.
A columnar store is not a job queue
Lance is a columnar analytical store. It is good at scanning a few columns over many rows. It is not a transactional row store, and joins are its weakness. A join can build a hash table from a full scan of one side; a predicate that looks selective in SQL can miss the btree index and degrade into a full fragment scan. Neither is a Lance bug; both are normal when a columnar format is asked to behave like an indexed OLTP table.
This is not about CPU-intensive work happening inside an OLAP query. It is that an OLAP query is the wrong place to repeatedly join what exists with what should exist. Using AI to program this made it easy to keep complex SQL queries: state tables held most of the traffic, including a high share of posts and comments, and joins pulled them together with what was not yet queried. That set difference belongs in a queue, where it is readily available.
From metric to plan
EXPLAIN ANALYZE added the missing sense (running DataFusion on top of Lance). Before it, every scan reported all fragments: fragments_scanned matched the fragment count of the whole table, no predicate pruned anything, and nothing failed. The plan now reports per-operator metrics, and the one that matters for a Lance scan is fragments_scanned=. That number is the difference between “the btree pruned this predicate to two fragments” and “this query read the whole table again”.
So the rule became: every query where an index is expected to prune gets its EXPLAIN ANALYZE plan into the integration test suite, and any filter or a join key counts. There is no allowance for a full scan. The shared helper runs EXPLAIN ANALYZE, extracts each Lance scan, and asserts on the fragment count:
pub async fn assert_index_pushdown(
store: &Store,
sql: &str,
params: Vec<datafusion::scalar::ScalarValue>,
filters: &[(&str, &str)],
fragments: &[(&str, u32)],
) {
let plan = explain_analyze(store, sql, params).await;
for (table, column) in filters {
assert_filtered(&plan, table, column);
}
for (table, max) in fragments {
assert_fragments(&plan, table, *max);
}
}
The tests use real fixtures with generated fragments and boundaries that should prune most of them.
The queue that now produces the work
The crawler discovers Reddit posts, re-checks their metrics at 1h, 2h, 4h, 8h, and 24h, and fetches the ones getting traction (if the rise is significant against the previous boundary). The durable output goes into Lance. The schedule is transient, so it lives in Redis.
discovery ──> check ──> flagged? ──> comments ──> Lance
Every queue is a Redis sorted set. Every queue owns two keys: q:<queue>:due holds the sorted set, q:<queue>:last the per-member bookkeeping hash. In the check queue the member is a Reddit fullname plus the age (t3_x:1h) and the score is the due time; in the comments queue the member is the bare fullname and the score is -num_comments.
| queue | member | score | claim order |
|---|---|---|---|
check | t3_x:1h … t3_x:24h | due time (epoch seconds) | only members with score <= now |
comments | t3_x | -num_comments | lowest score first, hottest post first |
ZADD q:check:due NX 1700003600 t3_x:1h
# set name due time member = post:ageHow a post moves through
- Discovery (
/r/all/new) pushes one job per future age into the check queue — membert3_x:1h, scorecreated_utc + age. Nothing is written to Lance yet: the queue is the only record of the schedule. - Each scheduler tick claims the due members and fetches them in
/api/infobatches of 100 ids. - A returned post must pass a subscriber-tiered comment threshold. Only then does it get a row in Lance and a job on the comment queue, where
-num_commentsputs the busiest threads first. - The observed count is kept in
q:comments:last; the next check re-queues comments only if the thread grew against it.
A post that misses the gate at every age is never stored anywhere. Its whole life in the system was five queue members and five /api/info responses.
One composite key, not one queue per age
All five land in that one check queue: five due times, five members, one sorted set. The due time is data, not part of a name: an age is a value the scheduler understands, and Redis only sorts by it.
This is also the shape everyone else landed on. Sidekiq has one schedule sorted set whose members are whole job payloads; Oban and River have one jobs table with a scheduled_at column. Nobody mainstream runs a key per time bucket.
The push is ZADD ... NX, so a re-discovery keeps the first due time. Because the members differ, the dedupe is per age — a bare post id would pin the post to its first due time and drop the other four.
The composite member pays for itself at claim time. A post that is overdue on 1h and 2h — after an hour of downtime, say — comes back as two members; the worker strips the age, dedupes by fullname, and fetches it once. The extra members are consumed with the claim, so one observation at claim time stands in for every age that was due, instead of one fetch per age.
Two claim orders
claim_dueis time order. It reads the due range and removes those members inside one atomic function invocation. The caller gets members back, so it strips the age and dedupes before the batch is fetched.claim_topis priority order. It pops the lowest scores first; Redis returns a flat member/score list, which the Rust client turns into(member, score)pairs. Comments use this: the score is-num_comments, so the worker recovers the count as-score.
Easy atomicity is the quiet win of Redis Functions. A function runs to completion on the single-threaded server, so the claim above is a read plus a remove with no WATCH/MULTI. The price is that a slow function blocks every other client, so each one stays a handful of sorted-set calls and nothing else. The sandbox enforces it: no network, no clock, so every function takes now as an argument.
The score does two jobs. First, it orders the comments queue: -num_comments makes the hottest post pop first, so claim_top is the priority list of comment fetches. Second, it carries the observed count through the claim; after a successful fetch the worker stores it in q:comments:last. When a check job comes due at 1h, 2h, 4h, 8h, or 24h, it reads that stored count, compares it with the fresh one, and only re-queues the post for comments if it grew enough. So the same number prioritizes the fetch and supplies the baseline for the next scheduled check.
Delivery guarantees
Claims consume the member: at-most-once, no lease, no retry. Redis AOF protects unclaimed work across a clean restart, but not in-flight work — and with appendfsync everysec a crash still loses up to the last second of pushes and claims. For a crawler, a lost check costs one observation; negligible; we are not a bank.
The queue’s server-side policy sits in the same Nix module as the daemon that uses it — NixOS turns this attribute set into systemd unit:
services.redis.servers.poller = {
enable = true;
port = redisPort;
bind = "127.0.0.1";
# unclaimed work survives a restart; in-flight does not
appendOnly = true;
# a crash costs at most the last second
appendFsync = "everysec";
# a queue must never be evicted
settings.maxmemory-policy = "noeviction";
};
Version 1 of the project used Redis Streams with consumer groups. That gave at-least-once delivery: each entry goes to one consumer, stays in the pending list until acknowledged, and can be retried. Multiple workers can compete safely, with Kafka-like ACK semantics and much less operational complexity. It fit a pipeline where several stages ran as separate consumers. Version 2 is less ambitious; not needing potential multi-server work distribution, so I traded that for simpler primitives: sorted sets and a few Lua functions. The workload also changed. V1 only looked at newly discovered posts and ignored comments; V2 re-checks the same post at 1h, 2h, 4h, 8h, and 24h and fetches comment trees. That came from user feedback.
Defined in Fennel
Redis Functions run in a Lua sandbox. Fennel compiles to ordinary Lua, so the whole server-side API is one source file, redis/queue.fnl. The core is three functions:
; key names the queue ("check"); the member carries the item ("t3_x:1h")
(local key-prefix "q:")
(fn due-key [q] (.. key-prefix q ":due"))
(fn push [_keys args]
(redis.call :ZADD (due-key (. args 1)) :NX (. args 2) (. args 3)))
(fn claim_due [_keys args]
(let [q (. args 1)
now (tonumber (. args 2))
limit (tonumber (. args 3))]
(if (< limit 1)
[]
(let [dk (due-key q)
ids (redis.call :ZRANGEBYSCORE dk :-inf (tostring now) :LIMIT :0
(tostring limit))]
(each [_ id (ipairs ids)]
(redis.call :ZREM dk id))
ids))))
(fn claim_top [_keys args]
(let [q (. args 1)
limit (tonumber (. args 2))]
(if (< limit 1)
[]
(redis.call :ZPOPMIN (due-key q) (tostring limit)))))
That is the queue: one sorted set per name, two claim orders, and no policy hidden in Redis. The rest of the file is bookkeeping — set_last_values, stats, ready. It is compiled into a Redis function library at build time:
redis-queue-lua = pkgs.runCommand "redis-queue-lua" {
nativeBuildInputs = [pkgs.lua5_1.pkgs.fennel];
} ''
mkdir -p $out
{ echo '#!lua name=queue'
fennel --compile ${./redis/queue.fnl}
} > $out/queue.lua
'';
No Fennel runtime inside Redis. The deployed artifact is plain Lua with the #!lua name=queue shebang Redis expects, loaded with redis-cli FUNCTION LOAD REPLACE under a systemd oneshot.
The version handshake is the part I would keep even without Fennel. library-version in the Fennel source and LIBRARY_VERSION in src/queue.rs must match. On startup, ready() compares them and fails loudly on a stale or half-deployed library. A flake check reads the Rust constant and compares it with the compiled Lua, so a one-sided version bump fails before deploying.
The second win is behaviour tests outside the host: redis/queue_test.fnl talks to a live Redis through redis-cli and checks the actual functions. devenv --profile redis-test test starts Redis, loads the library, runs the Fennel tests, then the Rust integration tests.
Verdict
Priority handling and automatic expiry belong in Redis. Permanent data that does not change belongs in a columnar store. LLM usage makes it easy to keep wrong design longer than deserved; however it also helps write the Fennel queue more elegantly than pure Lua.
Written with LLM assistance; the queue is real and really deployed.