Schedule Retries By Deadline With container/heap

Order pending retry jobs by earliest deadline and ID tie-breaker using container/heap, popping due work and pushing backed-off attempts.

GoResilience

Code

snippet
package main

import (
	"container/heap"
	"fmt"
)

type RetryJob struct {
	ID      string
	RunAtMs int
	Attempt int
}

type retryHeap []RetryJob

func (h retryHeap) Len() int { return len(h) }
func (h retryHeap) Less(i, j int) bool {
	if h[i].RunAtMs != h[j].RunAtMs {
		return h[i].RunAtMs < h[j].RunAtMs
	}
	return h[i].ID < h[j].ID
}
func (h retryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *retryHeap) Push(x any)   { *h = append(*h, x.(RetryJob)) }
func (h *retryHeap) Pop() any {
	old := *h
	item := old[len(old)-1]
	*h = old[:len(old)-1]
	return item
}

func main() {
	q := &retryHeap{
		{ID: "job-b", RunAtMs: 300, Attempt: 1},
		{ID: "job-a", RunAtMs: 100, Attempt: 1},
		{ID: "job-c", RunAtMs: 100, Attempt: 2},
	}
	heap.Init(q)

	for q.Len() > 0 {
		job := heap.Pop(q).(RetryJob)
		fmt.Printf("t=%dms run %s (attempt %d)\n", job.RunAtMs, job.ID, job.Attempt)
		if job.ID == "job-a" && job.Attempt == 1 {
			heap.Push(q, RetryJob{
				ID:      job.ID,
				RunAtMs: job.RunAtMs + 250,
				Attempt: job.Attempt + 1,
			})
		}
	}
}

Execution breakdown — Schedule Retries By Deadline With container/heap

Behavior is concentrated inside the routines Len, Less, Swap and Push — everything else is wiring.

Iteration happens inside for q.Len() > 0 — everything outside it runs once.

Watch out for

  • No external dependencies appear; native language capabilities suffice.

Applying it

Core function shape starts with func (h retryHeap) Len() int

The run prints t= — each prefix names the step that produced it.

Running the file executes main, which drives Len, Pop and Push in order.

Statements that matter

func (h *retryHeap) Push(x any)   { *h = append(*h, x.(RetryJob)) }
func (h retryHeap) Len() int { return len(h) }
func (h retryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }

Interactive Tools for This Topic

FAQ

What does Schedule Retries By Deadline With container/heap print when run?
Invoke the file as-is — the `t=` prefixes identify which step printed each line.