Queues & streams
medium 30 minA message queue stores work between the program that asks for it and the program that does it.
A work queue with receipts, timeouts and a dead letter queue
Read it, run it, change a line and run it again.
Loading editor…
Time is passed in, so the example is repeatable. Receives are counted, because a crashed worker cannot report a failure.
The same in TypeScript
interface Message { id: number; payload: unknown; visibleAt: number; receives: number; receipt?: number }class WorkQueue { private messages = new Map<number, Message>(); readonly dead: Message[] = []; private nextId = 1; private nextReceipt = 1000; constructor(private visibilityMs = 30_000, private maxReceives = 3) {} send(payload: unknown): number { const id = this.nextId++; this.messages.set(id, { id, payload, visibleAt: 0, receives: 0 }); return id; } receive(now: number, limit = 10): Message[] { const out: Message[] = []; for (const m of [...this.messages.values()]) { if (out.length === limit) break; if (m.visibleAt > now) continue; if (m.receives >= this.maxReceives) { this.messages.delete(m.id); this.dead.push(m); continue; } m.receives += 1; m.visibleAt = now + this.visibilityMs; m.receipt = this.nextReceipt++; out.push({ ...m }); } return out; } acknowledge(receipt: number): boolean { for (const m of this.messages.values()) { if (m.receipt === receipt) return this.messages.delete(m.id); } return false; }}const q = new WorkQueue();q.send({ orderId: "123" });const [first] = q.receive(0);const [again] = q.receive(30_001); // the first worker was too slowconsole.log(q.acknowledge(first.receipt!), q.acknowledge(again.receipt!)); // false trueThe same in Go
package mainimport ( "fmt" "sync" "time")type Message struct { ID int Payload string VisibleAt time.Time Receives int Receipt int}type WorkQueue struct { mu sync.Mutex messages []*Message Dead []*Message nextID int nextReceipt int Visibility time.Duration MaxReceives int}func (q *WorkQueue) Send(payload string) int { q.mu.Lock() defer q.mu.Unlock() q.nextID++ q.messages = append(q.messages, &Message{ID: q.nextID, Payload: payload}) return q.nextID}func (q *WorkQueue) Receive(now time.Time, limit int) []Message { q.mu.Lock() defer q.mu.Unlock() var out []Message keep := make([]*Message, 0, len(q.messages)) for _, m := range q.messages { ready := len(out) < limit && !m.VisibleAt.After(now) if ready && m.Receives >= q.MaxReceives { q.Dead = append(q.Dead, m) continue } keep = append(keep, m) if !ready { continue } m.Receives++ q.nextReceipt++ m.Receipt = q.nextReceipt m.VisibleAt = now.Add(q.Visibility) out = append(out, *m) } q.messages = keep return out}func (q *WorkQueue) Acknowledge(receipt int) bool { q.mu.Lock() defer q.mu.Unlock() for i, m := range q.messages { if m.Receipt == receipt { q.messages = append(q.messages[:i], q.messages[i+1:]...) return true } } return false}func main() { q := &WorkQueue{Visibility: 30 * time.Second, MaxReceives: 3} q.Send("order 123") for _, m := range q.Receive(time.Now(), 10) { fmt.Println("working on", m.Payload, q.Acknowledge(m.Receipt)) }}