Repository navigation
Introduce queue/v1: message queue over immutable edge tables - #437
Conversation
Empty commit to open the PR for queue/v1 over immutable edge tables (#428). Scope: enqueue + poll only; eviction is a separate follow-up. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sharding, partition hashing, and forward-only poll cursor for queue/v1 over immutable edge tables (#428). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Store queue metadata (partitionCount, orderBy) in the backing immutable edge table comment behind a `queue/v1` marker (#428). Co-Authored-By: Claude Opus 4.8 <[email protected]>
QueueAdminService builds an ImmutableEdge table via V3CompatService with a LONG partition source, STRING message-id target, and an indexed LONG orderBy. Validates orderBy/property names against v2 reserved fields. Delete deactivates then removes. Lifecycle E2E included (#428). Co-Authored-By: Claude Opus 4.8 <[email protected]>
QueueService.enqueue appends messages as INSERTs with lock=false (an append has no read-modify-write conflict), routing each message to a partition via PartitionHasher and reporting per-message status. E2E included (#428). Co-Authored-By: Claude Opus 4.8 <[email protected]>
QueueService.poll fans out a per-partition index scan across a shard's partitions, merges by orderBy, and returns a forward-only cursor. limit is per-partition; ordering is guaranteed within a partition. E2E covers order, cursor pagination, and shard split (#428). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The cursor now records the last-consumed orderBy per partition and resumes each scan with `orderBy:gt:position`, instead of opaque per-page scan offsets. Previously a drained partition dropped out of the cursor and was re-read from the start on the next poll. Carry every prior position forward so drained partitions yield nothing until higher-ordered messages arrive. Requires orderBy to be unique per partition (a monotonic sequence). (#428) Co-Authored-By: Claude Opus 4.8 <[email protected]>
…l limit Add /queue/v1 to ReadOnlyRequestFilter's guarded prefixes so queue writes (create/enqueue/delete) are rejected in read-only mode like graph writes, and classify the queue endpoints in ReadOnlyRequestFilterTest's exhaustiveness registry (the full build's endpoint scan required this). Also bound poll `limit` to 1..1000 to cap per-partition fan-out work. (#428) Co-Authored-By: Claude Opus 4.8 <[email protected]>
Instead of injecting a separate LONG orderBy field, orderBy now names one of the caller-declared properties (validated: present, LONG, non-nullable) and is indexed for order. Enqueue carries the order value inside the message payload, and poll returns the full declared properties intact (orderBy is also surfaced as a convenience projection). This drops the "magic field" and mirrors how ImmutableEdge's index + range predicate actually work. (#428) Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add QueueExpireTableE2ETest modeling the top-k _expire table: partition = hash(table|topk|entity) % 2310, id = table|topk|entity|expiredAt, and expiredAt as the orderBy so entries poll in due order (oldest expiry first). Drives the QueueAdminService/QueueService beans directly (no HTTP) to show another controller's workflow can control a queue programmatically. (#428, #386) Co-Authored-By: Claude Opus 4.8 <[email protected]>
30 = 2·3·5 (divisors 1,2,3,5,6,10,15,30) keeps shard=k/N splits balanced while keeping single-shard poll fan-out cheap; 480 was needlessly high for the poll scan-per-partition cost. (#428) Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ify partitionCount to 30 Rewrite QueueExpireTableE2ETest to exercise create -> enqueue -> poll over HTTP (expiredAt as orderBy, due-first poll), and add a second angle where a workflow enqueues through the QueueService bean and the entries are polled back over HTTP (proving another controller's workflow can drive the queue). Unify sample partition counts to 30 to match the new default. (#428, #386) Co-Authored-By: Claude Opus 4.8 <[email protected]>
queue/v1 — finalized designA queue is an Data model — queue ↔ immutable edge table
Immutable specifics: no State row (a write persists index records only — the ASC API — every endpoint lowers to a v3 call
Enqueue —
|
| enqueue field | edge |
|---|---|
key |
floorMod(xxHash32(key), partitions) = source; not stored |
(server) ULID.random() |
target (id) |
seq |
property seq (= edge version) |
value (any JSON) |
property value (JSON string) |
Response: { accepted, results: [{ partition, id, status }] }, where id is the assigned ULID.
Poll — request → edge scan
GET .../partitions/7/poll?limit=100&offset=1730000000000&until=1730000009999
# lowers to
GET /graph/v3/databases/mydb/tables/events/edges/scan/seq?start=7&direction=OUT&limit=100&ranges=seq:bt:1730000000001,1730000009999
# without `until` -> ranges=seq:gt:1730000000000
| poll param | edge scan | note |
|---|---|---|
partition |
start |
source |
| (fixed) | direction=OUT |
|
limit |
limit |
|
offset |
ranges=seq:gt:offset (or bt lower offset+1) |
exclusive lower bound — a range predicate, not the scan's own offset |
until |
ranges=seq:bt:…,until |
inclusive upper; refresh passes now, so not-yet-due rows are never returned |
index seq |
.../scan/seq |
the ASC index |
| — | offset (opaque token) |
unused — the queue resumes by seq value |
Poll — response ← edge scan
edge scan (DataFrameEdgePayload) |
poll | transform |
|---|---|---|
edges[].source |
messages[].partition |
Long → Int |
edges[].target |
messages[].id |
ULID |
edges[].properties.seq |
messages[].seq |
as-is |
edges[].properties.value |
messages[].value |
JSON → parsed (any) |
offset (opaque String) |
offset (LONG) |
replaced with max(seq) |
hasNext |
hasNext |
pass-through |
version / count / total / context |
(dropped) | total unsupported on immutable |
offset is the same field in and out (like the edge scan) and is retained when a partition drains, so later appends / newly-due rows are picked up on the next poll. Consumers shard by owning a subset of 0 .. partitions-1; the server does no cross-partition fan-out or merge.
Create — body → TableCreateRequest
| queue create | TableCreateRequest |
|---|---|
queue |
table |
storage |
storage |
partitions |
comment — queue/v1 {"partitions":N} |
| (fixed) | schema — ImmutableEdge (seq LONG + ASC index, value STRING) |
| (fixed) | mode — SYNC |
Get — TableDescriptor → queue metadata
TableDescriptor |
queue metadata |
|---|---|
database |
namespace |
table |
queue |
comment marker |
partitions (decoded) |
storage |
storage |
active / schema / indexes |
(hidden) |
Invariants
| invariant | why |
|---|---|
id = ULID (80-bit entropy) |
per-partition target uniqueness → no collision loss |
seq is a monotonic client-supplied ordering key (timestamp / LSN / sequence) |
the LSM-backed seq index scans in order, so per-partition delivery is sorted — the queue's contract; strict uniqueness is not required |
seq index is ASC |
oldest → newest replay (WAL/CDC and refresh order) |
Follow-up
rename databases → namespaces, partitionCount → partitions; drop orderBy config and user properties; enqueue { key, seq, value } + ULID id; poll per-partition offset / until → gt / bt; lifecycle PUT /enable · /disable + delete active-guard; remove Shard and QueueCursor.
Out of scope / TBD follow-up: eviction / retention via a background scan-and-delete sweep over the ImmutableEdge (append-only writes, but deletion is allowed — only in-place update is not).
A queue is an engine capability over the immutable edge table, so the
runtime (enqueue/poll) moves into com.kakao.actionbase.engine.queue
(QueueService, PartitionHasher, QueueDescriptorCodec, QueueSchema,
payloads), wired as a bean in GraphConfiguration. The server keeps a
thin HTTP layer (MessageController) and queue DDL under
api/queue/v1/metadata (QueueController + QueueMetadataService).
Finalize the API:
- paths use namespaces/{ns} and partitions (was databases/partitionCount)
- message = {key, seq, value}; id is a server-assigned ULID; value is an
opaque any-JSON blob (seq and value are fixed system fields)
- poll is per-partition with offset (seq:gt) plus optional until (seq:bt)
for refresh/delay queues; response carries offset + hasNext
- lifecycle: PUT enable/disable, delete guarded (409 unless inactive)
- remove Shard and QueueCursor
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Rename QueueAdminE2ETest to QueueLifecycleE2ETest and scrub the remaining "admin" strings (namespace, storage, QueueSchema doc) now that the DDL surface lives in api/queue/v1/metadata. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… add partitions endpoint
Runtime partition-count reads (enqueue routing, poll range check) now use
Graph's in-memory label registry via getLabel — refreshed by the periodic
metastore reload — instead of a fresh metastore read per request. No extra
caching layer. A queue not yet picked up by a reload is simply not visible
yet (E2E warms the registry with Graph.updateLabels after create).
Add GET /queue/v1/namespaces/{ns}/queues/{queue}/partitions returning the
partition count from the same in-memory source, for consumers that fan a
poll loop across 0..partitions-1.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cache the decoded partition count keyed by (namespace, queue) so enqueue routing and the poll range check neither read the metastore nor re-parse the comment marker on every request. Expire-after-write (1 min), not -access, bounds staleness so a re-partitioned queue (the size can change) is picked up within ~1 minute; a cache miss reads Graph's in-memory registry and decodes the marker. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cut verbose KDoc down to one-line docs where they earn their place, and collapse QueueSchema.SEQ_FIELD/SEQ_INDEX into a single SEQ (the index is named after the field it indexes); VALUE_FIELD -> VALUE. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add Bean Validation to QueueCreateRequest — @notblank + name/storage @pattern (Constants.Name) and @min(1) on partitions — wired via @validated + @Valid on the DDL controller, which also runs path names through V3NameValidator (mirroring TableController). Drop the now-redundant partitions require in the service. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Scope & fitqueue/v1 is a durable, partitioned, append-only log over the immutable edge table, with a due-time filter for refresh / delay use. It is a log primitive, not a full message broker — so it fits some use cases cleanly and not others. What works end-to-end
Fit by use case
Key gaps
Refresh / delay is the best current fit. WAL/CDC becomes practical once retention (the eviction follow-up) lands; it is not a drop-in Kafka replacement. It is not an ack-based work queue. |
…at once createQueue now forces graph.updateLabels() after the DDL create, so the runtime (which reads partition metadata from Graph's in-memory registry via getLabel) sees the new queue immediately — instead of failing until the next metastore reload, which may be long or disabled (e.g. a plain local ServerApplication run). Drops the manual updateLabels warm-up the E2E tests needed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
queue/v1 interactive end-to-end demo.queue_v1_demo.go// BASE=http://localhost:8080 NS=demo_ns Q=events go run queue_v1_demo.go
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strings"
"time"
)
const (
b, d, r = "\033[1m", "\033[2m", "\033[0m"
red, grn, yel, blu, mag, cyn = "\033[31m", "\033[32m", "\033[33m", "\033[34m", "\033[35m", "\033[36m"
)
var (
base = env("BASE", "http://localhost:8080")
ns = env("NS", "demo_ns")
q = env("Q", "events")
stdin = bufio.NewReader(os.Stdin)
keyRe = regexp.MustCompile(`"([^"\\]+)":`)
step = 0
)
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
func pause() {
fmt.Printf("\n%s ↵ Enter to send (Ctrl-C to quit)%s", d, r)
stdin.ReadString('\n')
}
func hr() { fmt.Printf("%s%s%s\n", d, strings.Repeat("─", 62), r) }
// colorJSON indents and tints object keys.
func colorJSON(raw []byte) string {
var buf bytes.Buffer
if json.Indent(&buf, raw, "", " ") != nil {
return string(raw)
}
return keyRe.ReplaceAllString(buf.String(), yel+`"$1"`+r+":")
}
func doReq(method, path, body string) (int, []byte) {
var rdr io.Reader
if body != "" {
rdr = strings.NewReader(body)
}
req, _ := http.NewRequest(method, base+path, rdr)
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("\n%srequest failed: %v%s\n", red, err, r)
os.Exit(1)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
return resp.StatusCode, data
}
// stripTrace drops the (huge) stack trace Spring adds to error bodies.
func stripTrace(body []byte) []byte {
var m map[string]any
if json.Unmarshal(body, &m) != nil {
return body
}
if _, ok := m["trace"]; !ok {
return body
}
m["trace"] = "(stack trace omitted)"
if out, err := json.Marshal(m); err == nil {
return out
}
return body
}
func showRes(code int, body []byte) {
sc := grn
if code >= 400 {
sc = red
}
fmt.Printf("%s← HTTP %s%d%s\n", b, sc, code, r)
body = stripTrace(body)
if len(bytes.TrimSpace(body)) > 0 {
fmt.Println(colorJSON(body))
}
}
// call = header + request + pause + send + response; returns the parsed body.
func call(title, desc, method, path, body string) map[string]any {
step++
fmt.Println()
hr()
fmt.Printf("%s%s[%d] %s%s\n%s%s%s\n", b, mag, step, title, r, d, desc, r)
fmt.Printf("\n%s%s%s %s%s%s\n", b+cyn, method, r, blu, base+path, r)
if body != "" {
fmt.Printf("%srequest:%s\n%s\n", d, r, colorJSON([]byte(body)))
}
pause()
code, data := doReq(method, path, body)
showRes(code, data)
var m map[string]any
json.Unmarshal(data, &m)
return m
}
func partitionOf(m map[string]any) int {
if res, ok := m["results"].([]any); ok && len(res) > 0 {
if first, ok := res[0].(map[string]any); ok {
if p, ok := first["partition"].(float64); ok {
return int(p)
}
}
}
return 0
}
func offsetOf(m map[string]any) string {
if v, ok := m["offset"].(float64); ok {
return fmt.Sprintf("%.0f", v)
}
return ""
}
func main() {
fmt.Printf("%s%squeue/v1 — interactive end-to-end demo%s\n", b, mag, r)
fmt.Printf("%sbase=%s namespace=%s queue=%s%s\n", d, base, ns, q, r)
fmt.Printf("%sEach step prints the request; press Enter to send it and see the response.%s\n", d, r)
qpath := "/queue/v1/namespaces/" + ns + "/queues/" + q
storage := fmt.Sprintf("datastore://%s/%s", ns, q)
call("Create the namespace", "A queue namespace is a v3 database.",
"POST", "/graph/v3/databases",
fmt.Sprintf(`{"database":%q,"comment":"queue demo"}`, ns))
call("Create the queue", "No schema to declare — seq (order), value (opaque body) and the ULID id are system fields.",
"POST", "/queue/v1/namespaces/"+ns+"/queues",
fmt.Sprintf(`{"queue":%q,"storage":%q,"partitions":8}`, q, storage))
call("Inspect the queue", "Create forces a metadata sync, so the queue is usable immediately.",
"GET", qpath, "")
call("Get the partition count", "Consumers use this to fan a poll loop across 0..partitions-1.",
"GET", qpath+"/partitions", "")
now := time.Now().UnixMilli()
enq := fmt.Sprintf(`{"messages":[
{"key":"user-1","seq":%d,"value":{"body":"a"}},
{"key":"user-1","seq":%d,"value":"just-a-string"},
{"key":"user-1","seq":%d,"value":[1,2,3]}
]}`, now-3000, now-2000, now-1000)
er := call("Enqueue a batch", "key routes to a partition (hash), seq orders it, value is any JSON; the server assigns each ULID id. Same key → same partition.",
"POST", qpath+"/messages", enq)
part := partitionOf(er)
poll := fmt.Sprintf("%s/partitions/%d/poll", qpath, part)
fmt.Printf("\n%s→ landed in partition %s%d%s%s; polling it next.%s\n", d, b, part, r, d, r)
pr := call("Poll the partition", "One partition, seq ascending. 'offset' comes back as the forward cursor.",
"GET", poll+"?limit=10", "")
off := offsetOf(pr)
call("Poll again from the cursor", "offset="+off+" resumes strictly after it — the partition is now drained (empty page).",
"GET", poll+"?limit=10&offset="+off, "")
now = time.Now().UnixMilli()
enq2 := fmt.Sprintf(`{"messages":[
{"key":"user-1","seq":%d,"value":{"note":"due now"}},
{"key":"user-1","seq":%d,"value":{"note":"due in 1h"}}
]}`, now-500, now+3600000)
call("Enqueue a 'due now' and a 'due later' message", "seq doubles as a due-time (epoch ms): one just passed, one is an hour out.",
"POST", qpath+"/messages", enq2)
call("Poll only what's due (refresh queue)", fmt.Sprintf("until=%d bounds the poll — the future message is withheld, so a scheduler never fires early.", now),
"GET", fmt.Sprintf("%s?limit=10&offset=%s&until=%d", poll, off, now), "")
call("Try to delete while active (guarded)", "Delete is refused with 409 until the queue is disabled.",
"DELETE", qpath, "")
call("Disable the queue", "PUT .../disable flips the active flag (idempotent).",
"PUT", qpath+"/disable", "")
call("Delete the queue", "Now that it is inactive, delete succeeds (204).",
"DELETE", qpath, "")
fmt.Println()
hr()
fmt.Printf("%s%sdone.%s\n", b, grn, r)
}output |
- Consistent naming: internal code uses `numPartitions` (Spark-style) while the HTTP/DTO surface keeps `partitions`. Completes the rename across the poll lambda, the cache (numPartitionsCache / NUM_PARTITIONS_CACHE_SIZE), PartitionHasher, and tests. - Harden the poll seq read: `as? Number ?: error(...)` instead of a hard `as Number` cast, so a malformed/non-queue edge fails with a clear message rather than an NPE/ClassCastException. - Trim a WHAT-style comment. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The queue-config concept was named three ways (QueueMeta, QueueDescriptorCodec, QueueMetadataService). Standardize on "Metadata" for the config/DDL concept and reserve "Descriptor" for the API response DTO (matching core TableDescriptor): - QueueMeta -> QueueMetadata - QueueDescriptorCodec -> QueueMetadataCodec (name now matches the type it codecs) - files/tests renamed accordingly - QueueDescriptorResponse, QueueMetadataService, and the metadata package unchanged Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
queue/v1: Kafka-style log over immutable edge tables
queue/v1: Kafka-style log over immutable edge tablesqueue/v1: message queue over immutable edge tables
Summary
queue/v1 is a message queue that also serves as a refresh / delay queue. It is an engine capability: the runtime (enqueue / poll) lives in
engine(com.kakao.actionbase.engine.queue) over the immutable edge table, with a thinserver/HTTP layer and queue DDL (create / enable / disable / delete) over the v3 table API.A queue is an
ImmutableEdgetable:source= partition,target=id(server-assigned ULID), a LONGseqproperty indexed ASC for per-partition order, and an opaquevalue(any JSON). Enqueue is a lock-free append; poll is a per-partition range scan overseqwith a forwardoffsetcursor and an optionaluntilupper bound (refresh / delay).Message =
{ key, seq, value }; endpoints under/queue/v1/namespaces/{ns}/queues. Full design — data model, and how every endpoint lowers to a v3 edge scan / table DDL — is in the design comment below.Scoped to admin + enqueue + poll. Eviction / retention is a TBD follow-up — a background scan-and-delete sweep over the
ImmutableEdge(which forbids in-place update, not deletion) — tracked separately.Closes #428
Changes
com.kakao.actionbase.engine.queue) —QueueService(enqueue / poll),PartitionHasher,QueueDescriptorCodec,QueueSchema, and the runtime payloads. Enqueue appends viaMutationService.mutateINSERT withlock=falseand assigns the ULIDid; poll is a single-partitionseq-index scan (seq:gt:offsetfor a log,seq:bt:offset+1,untilfor refresh). Wired as a bean inGraphConfiguration.api/queue/v1) —MessageController(enqueue / poll) delegating to the engine;api/queue/v1/metadata/QueueController+QueueMetadataServicebuild / inspect / toggle / delete the backing table overV3CompatService, with delete guarded (409unless inactive).No changes to the core immutable-edge binding — the queue reuses it as-is.
How to Test
./gradlew :engine:test --tests "com.kakao.actionbase.engine.queue.*"—PartitionHasher, descriptor codec../gradlew :server:test --tests "*queue.v1.*"— E2E (admin lifecycle incl. enable / disable / delete-guard, enqueue with ULIDid, poll order / pagination /until)../gradlew :engine:spotlessCheck :server:spotlessCheck.AI Assistance