Event Streaming Architecture
How events flow through the Virtufin API: CloudEvents over Dapr pub/sub, exposed to clients as gRPC streams.
Overview
Every event on the platform is a CloudEvents v1.0
message. The API is the only component that talks to Dapr pub/sub; other services publish
and subscribe through the Pubsub gRPC service.
| Mechanism | Direction | Entry point |
|---|---|---|
Pubsub.PublishEvent / PublishEvents |
client → Dapr topic | unary gRPC |
Pubsub.Subscribe |
Dapr topic → client | server-streaming gRPC |
Trigger.ScheduleTrigger |
cron → Dapr topic | unary gRPC |
State.SaveState(publish_change: true) |
state write → sys.api.state.saved/deleted topic |
unary gRPC |
The wire type
Events are the CloudEvent protobuf message (proto/cloudevents.proto,
package io.cloudevents.v1), not a bespoke envelope:
message CloudEvent {
string id = 1;
string source = 2; // MUST be an absolute URI — see validation below
string spec_version = 3;
string type = 4; // "ce-type"; discriminates events within a topic
map<string, CloudEventAttributeValue> attributes = 5; // optional + extension attributes
oneof data {
bytes binary_data = 6;
string text_data = 7;
google.protobuf.Any proto_data = 8;
}
}
The Pubsub service surface (proto/pubsub.proto):
service Pubsub {
rpc ChangePublicationFence (ChangePublicationFenceRequest) returns (ChangePublicationFenceResponse);
rpc PublishEvent (PublishRequest) returns (PublishResponse);
rpc PublishEvents (PublishEventsRequest) returns (PublishEventsResponse);
rpc Subscribe (SubscribeRequest) returns (stream SubscribeResponse);
rpc ListTopics (ListTopicsRequest) returns (ListTopicsResponse);
}
message PublishRequest { string topic = 1; io.cloudevents.v1.CloudEvent cloudevent = 2; }
message SubscribeRequest {
repeated string topics = 1;
google.protobuf.Timestamp replay_since = 2;
bool replay_only = 3;
bool announce_live = 4;
bool accept_batches = 5;
}
message SubscribeResponse {
string topic = 1;
io.cloudevents.v1.CloudEvent cloudevent = 2;
bool live = 3; // only with announce_live
bytes batch = 4; // only with accept_batches: an encoded io.cloudevents.v1.CloudEventBatch
}
This is the CloudEvents protobuf format:
cloudevents.proto is the specification's file, unchanged. The gateway also stores
every event in that form, so an event is protobuf from the publisher to the subscriber
and an attribute arrives in the type it was sent in. The one exception is time, which
is stored as a timestamp even when it was sent as a string. See
How events are stored.
SubscribeRequest filters by topic only. There is no service filter and no event-type
filter on the wire; a subscriber that wants to react to a subset of a topic's events
inspects cloudevent.type itself.
Publish validation
PublishEvent rejects, with InvalidArgument:
- an empty
topic; - a missing
cloudevent; - an empty
cloudevent.source; - a
cloudevent.sourcethat is not an absolute URI."demo/notebook"is rejected;"https://virtufin.com/demo/notebook"and"urn:virtufin:demo"are accepted.
Nothing else about a topic is validated — see "Topic naming" below.
Topic naming
Every topic comes from the naming library (sys.<service>.<entity>.<event> for Tier 0;
see the naming docs and this repo's naming tables):
| Topic | Publisher | Contents |
|---|---|---|
sys.workmanager.worker.lifecycle |
WorkManager | worker lifecycle, including the status events workers report (a WebSocketFeed reports connecting, connected, reconnecting, disconnected, degraded, releasing this way) |
sys.api.state.saved/deleted |
the API itself | state mutations (see below) |
Each publishing service defines its names in its own naming fragment (naming/*.yaml),
which is the public contract between that publisher and its consumers. The state of a
lifecycle event travels in the payload's state field, not in the topic or the ce-type.
This convention is producer-side discipline, not an API guarantee. The API does not validate topic names against the convention, does not maintain an allow-list, and does not scope topics to callers. Any authenticated caller may publish to, and subscribe to, any topic string — including another service's lifecycle topic and
sys.api.state.saved/deleted. Do not rely on the topic namespace for isolation.
State change events
State.SaveState, State.DeleteState and State.DeleteBulkState accept a
publish_change flag. When set, the API publishes a change notification after the
write succeeds. Emitting one is opt-in per request — it is not a property of every state
change.
Where that notification goes depends on what kind of state you wrote.
Infrastructure state → sys.api.state.saved / sys.api.state.deleted (Tier 0)
Records whose owner is a platform service and whose meaning is deployment-scoped — worker
registrations, connection records, leader leases. Leave change unset and the API
publishes to the global sys.api.state.saved / sys.api.state.deleted topics with:
type=com.virtufin.api.state.savedorcom.virtufin.api.state.deleted, so subscribers can filter on the action without parsing the payload;source=urn:com.virtufin:api, the publishing service.
{
"service": "workmanager",
"key": "sys.workmanager.worker.abc123",
"action": "save",
"value": "the-state-value"
}
action is "save" or "delete". value appears only when the request sets
include_value: true. DeleteBulkState publishes a keys array in place of key, and
names only the keys actually deleted.
These events carry no version, and cannot. Dapr's state API returns no etag from a write, and re-reading the key to get one would be worse than omitting it: a concurrent writer may have advanced the value in between, so the event would attribute a newer version to an older payload. A subscriber consuming
valueinstead of reading state back is therefore relying on writes to that key being serialized. Where you need a real ordering guarantee, use the Tier 1 path below.
sys.api.state.saved and sys.api.state.deleted are shared, unscoped topics, so include_value: true publishes that
value to every subscriber of it.
Domain state → your own topic (Tier 1)
Records that are scenario- or universe-scoped — positions, portfolios, orders, risk and
P&L artifacts. These do not belong on sys.api.state.saved/deleted: which service performed the
write is an implementation detail, and subscribers route on the domain topic.
The API cannot build that event for you. It has the store, the key and the bytes, but not
the scenario, the world markers, the clock type, or your service's identity. So supply
the whole CloudEvent and the topic it belongs on, via the change field:
{
"service": "workmanager",
"key": "workmanager.position.BTCUSDT",
"value": "{\"qty\":3}",
"publish_change": true,
"change": {
"topic": "sc.LIVE.position.snapshot",
"cloudevent": {
"id": "…",
"type": "com.virtufin.position.flipped",
"source": "urn:com.virtufin:trading-engine",
"spec_version": "1.0",
"text_data": "{\"symbol\":\"BTCUSDT\",\"qty\":3}"
}
}
}
The API publishes that event verbatim to that topic once the write lands, and does not
also publish to sys.api.state.saved/deleted — publishing to both would double-deliver the change.
Set both topic and cloudevent. A change with only a topic falls back to the Tier 0
path: half a notification is not a Tier 1 event.
Because you control the envelope, this is where ordering lives: if subscribers consume
your payload instead of reading state back, carry a monotonic token (a domain version,
sequence number, or eventtime where the clock is authoritative) and have them discard
anything not newer. Only you know how the entity is versioned.
Do not reach for a
sys.api.state.saved.<state_name>topic. A Tier 0 topic names an entity and a kind of event, not a state, and per-key topics contradict the platform's cardinality rule. Domain state belongs on the Tier 1 taxonomy, which already has topics your subscribers subscribe to.
Delivery
Publication is at-most-once and is not atomic with the write. If the write succeeds and the publish fails, the event is lost — the API logs it and still reports the write as successful, because failing the call would make you repeat a write that already landed. Design subscribers to reconcile from state rather than assuming every change produced an event.
Measuring the gap
A lost event is otherwise invisible: no retry, no dead letter, and the caller sees success. Two counters make it countable:
| Metric | Meaning |
|---|---|
virtufin_api_state_change_publishes_total |
notifications attempted, after a successful write |
virtufin_api_state_change_publish_failures_total |
of those, the ones lost |
Both are tagged service, action (save/delete) and tier (tier0/tier1) — the
tiers are separated because a lost Tier 1 domain event matters considerably more than a
lost Tier 0 infra notification.
They are exported over OTLP only when OTEL_EXPORTER_OTLP_ENDPOINT is set. There is
no collector in the deployment today, so until one exists the metrics are collected
in-process and go nowhere, and the structured log is the measurement path:
State change publish failed after a successful write: service=… key=… topic=… tier=…
logged at Error from StateService. Counting those occurrences over a period is what
should decide whether the at-most-once gap is worth closing with a transactional outbox —
which would flip the guarantee to at-least-once and make every subscriber's idempotency a
breaking concern. That trade is worth making for a frequent failure and not for a rare
one, and nothing measured it before.
Subscribing
Pubsub.Subscribe is server-streaming: one call, many SubscribeResponse messages, one
gRPC stream per client call regardless of how many topics it names.
using var call = pubsubClient.Subscribe(
new SubscribeRequest { Topics = { "workmanager.lifecycle" } });
await foreach (var evt in call.ResponseStream.ReadAllAsync(cancellationToken))
{
Console.WriteLine($"{evt.Topic}: {evt.Cloudevent.Type}");
}
Behaviors worth knowing:
- An empty
topicslist is not "all topics". It silently defaults to["sys.api.state.saved", "sys.api.state.deleted"]. Name your topics explicitly. - Duplicate topics in one request produce duplicate delivery of each event to that caller.
- Each subscriber buffers up to 1024 events. A consumer that falls further behind
than that loses nothing: the gateway serves it from the topic's stream at its own pace
until it has caught up. Its call ends with
DataLossonly when it is behind further than the stream reaches back, and withResourceExhaustedwhen it takes nothing forPubsubSubscriberStallSeconds. See TopicDaprSubscriptionRegistry. accept_batchesasks for whole batches. The events onePublishEventscall sent for a topic then arrive as one response, inbatch, instead of one response per event. Same events, same order; an event stored alone still arrives incloudevent. Meant for a subscriber that takes events in bulk; the client wrappers do not set it. See Subscribe.- One shared Dapr subscription per topic per process, reference-counted across callers
(
TopicDaprSubscriptionRegistry). This is deliberate: a Dapr subscription per caller would make daprd load-balance each event across callers instead of broadcasting it. - Initial response headers are flushed before any event arrives. Request-reply clients depend on this to know the subscription is live before they publish; see below.
announce_liveasks for the same news in the stream. With it, the first response islive = true, without a topic or an event, sent right after the headers. Use it where the headers are not visible on their own: a browser'sfetch()in Firefox resolves only with the first body bytes, so over gRPC-Web a quiet topic would otherwise never look live. Withoutannounce_livenothing changes: every response carries an event. Ignored withreplay_only.- Canceling the call is the teardown. Disposing the streaming call removes the subscriber; the last one leaving closes the shared Dapr subscription.
- A failed Dapr subscription ends the stream. If the sidecar stream for a topic fails,
every Subscribe on that topic ends with
Unavailable; resubscribe (the clients' reply readers do this with backoff).
Cron triggers
Trigger.ScheduleTrigger schedules a recurring job through Dapr's Scheduler. When it fires,
DaprAppCallbackService publishes an empty CloudEvent to the trigger's target_topic
(type = com.virtufin.api.trigger.fired, source = urn:com.virtufin:api). The trigger carries no payload;
subscribers react to the fact that it fired.
New topics → sys.api.topic.catalog.added (Tier 0)
When the topic catalog (ListTopics) gains topics, the gateway publishes
com.virtufin.api.topic.catalog.added on sys.api.topic.catalog.added with
{topics: [...]}: once per topic, cluster-wide, a few seconds after the topic's
first traffic (the catalog merges every 5 s). Best effort; see
Services.
Consumer progress → sys.api.pubsub.progress.reported (Tier 0)
Each ReportProgress call is published once as com.virtufin.api.pubsub.progress.reported
on sys.api.pubsub.progress.reported. Its data is the encoded ReportProgressRequest
(protobuf). Every gateway pod applies it, so paced publishes on any pod wait on every
consumer's position. It is the gateway's own topic; clients report through
ReportProgress and never publish on it. See
Paced publishing.
Trigger changes → sys.api.trigger.scheduled / sys.api.trigger.deleted (Tier 0)
A successful ScheduleTrigger publishes com.virtufin.api.trigger.scheduled on
sys.api.trigger.scheduled, with the trigger's definition as data (TriggerScheduled):
{id, schedule, due_time, repeats, ttl, target_topic, owner_worker_id, tags, groups}. The
same event is published again whenever the trigger's tags, groups or owner change
(UpdateTriggerTags, AddTriggerToGroup, RemoveTriggerFromGroup, ClearTriggerOwner),
so it always carries the whole current definition. A successful DeleteTrigger publishes
com.virtufin.api.trigger.deleted on sys.api.trigger.deleted, with {id}. See
Triggers. A client keeps its list of triggers current from these events: one
ListTriggers when its subscription is live, then the events, with no polling (api#55).
These events are best effort, like the state-change events. The change has landed when
they are published, so a failed publish is logged and does not fail the call. A one-shot
trigger that ran out, or a job the scheduler dropped, is not announced. Reconcile with
ListTriggers after a resubscription.
Configuration
The Dapr pub/sub component name defaults to "pubsub" and is configurable, in this
precedence:
--pubsub-name(or thePubsubNamesetting);pubsub.pubsubNameinservices.json, which helm renders from.Values.pubsub.name;- the
"pubsub"default.
It is a gateway-wide setting despite living on each service entry.
PublishEventandSubscribetake a topic and no service, so there is nothing to resolve a per-service component against at call time. Every registered entry must therefore agree on the value — helm renders one value into all of them — and the gateway fails at startup if they disagree rather than silently picking one.
Subscriptions are created programmatically at runtime via Dapr's streaming-subscription API, not declared in YAML. The API's declarative subscription callback therefore returns an empty list by design.
Error handling
An OK status means the event was published. Every failure is a non-OK gRPC status with a
google.rpc.ErrorInfo (Errors):
| Failure | Status | Reason |
|---|---|---|
Invalid input (empty topic, bad source) |
INVALID_ARGUMENT |
INVALID_FIELD, with the field (topic, events[1].cloudevent.source) |
| Runtime failure (sidecar down, publish rejected) | UNAVAILABLE |
UNAVAILABLE, with the topic |
PublishEvents that published only some events |
ABORTED |
PARTIAL_FAILURE, with a PublishEventsFailure detail |
try
{
await pubsubClient.PublishEventAsync(new PublishRequest { Topic = topic, Cloudevent = ce });
}
catch (RpcException ex) when (ex.ErrorInfoOf() is { } error)
{
logger.LogWarning("Publish failed: {Reason} {Field}", error.Reason, error.Field);
}
On the subscribe side, handle stream termination as a normal condition and reconnect with backoff:
try
{
await foreach (var evt in call.ResponseStream.ReadAllAsync(token))
ProcessEvent(evt);
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
// Client disconnected — normal shutdown.
}
Why request-reply lives in the clients: Request-reply over pub/sub. Publishing and subscribing from each client: Publish and subscribe.