KubeMQ
Client SDKsElixirHow-to guidesEvents Store

Start from Last

Subscribe to a KubeMQ Events Store channel to receive only the most recent stored event, in Elixir.

Overview

A subscriber that just restarted usually doesn't need the entire event history — it needs to know where things stand right now without paying the cost of replaying everything that happened while it was offline. :start_from_last solves that: it re-anchors a new subscription to the tail of the store, delivering exactly one historical event (the most recently stored one) before switching to live delivery. That's the sweet spot between :start_from_new (no history at all, so you might miss the current state entirely) and :start_from_first (the full backlog, which can be slow and mostly irrelevant for a consumer that only cares about "now").

Under the hood, start_at: :start_from_last is passed as a subscription option. The broker looks up the channel's most recent stored event at subscription time, replays that single event to the new subscriber, and then streams every subsequently published event as it arrives — the same live path any other subscription uses.

Gotchas: if the channel is empty when you subscribe, there's no "last" event to deliver — you simply start receiving new events as they're published, with no error raised. :start_from_last gives you one event, not the last N — if you need a short window of recent history, replay from a sequence number instead. And because "last" is resolved at subscribe time, two subscribers starting a few events apart can each get a different one.

Prerequisites

  • KubeMQ server running on localhost:50000
  • Elixir SDK installed ({:kubemq, "~> 1.0"} in mix.exs)

Code

main.exs
channel = "elixir-events-store.start-from-last"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "elixir-es-last")

for i <- 1..5 do
  {:ok, _} = KubeMQ.Client.send_event_store(client,
    KubeMQ.EventStore.new(channel: channel, body: "Event #{i}"))
end

IO.puts("Stored 5 events")
parent = self()

{:ok, sub} =
  KubeMQ.Client.subscribe_to_events_store(client, channel,
    start_at: :start_from_last,
    on_event: fn event ->
      IO.puts("Received: #{event.body} (seq: #{event.sequence})")
      send(parent, :received)
    end
  )

receive do
  :received -> IO.puts("Got the last stored event!")
after
  5_000 -> IO.puts("Timeout")
end

KubeMQ.Subscription.cancel(sub)
KubeMQ.Client.close(client)

How It Works

  • :start_from_last delivers only the most recently stored event, then switches to live delivery
  • Earlier events (1–4 in this example) are skipped
  • Useful when you only need the latest state, not full history

Was this page helpful?

On this page