Architecture
Detailed architecture documentation for the Virtufin API gateway.
System Overview
Virtufin API is a gRPC-based API gateway that provides:
- Service Discovery - Dynamic discovery via gRPC reflection
- Method Invocation - Transparent forwarding to backend services
- Event Streaming - gRPC streaming and Dapr pub/sub
- State Management - Dapr state store integration
- Multi-Protocol Support - native gRPC and gRPC-Web, both on the gRPC port; the HTTP port serves only the health checks
System Architecture
flowchart TB
subgraph Clients["Clients"]
CSharp[C# Client]
Python[Python Client]
Browser[Browser<br/>gRPC-Web]
end
subgraph ProtocolLayer[Protocol Layer]
Shared[gRPC + gRPC-Web<br/>gRPC port :5002, HTTP/2]
Probes[Health checks only<br/>HTTP port :5001, HTTP/1.1]
end
subgraph ApplicationLayer["Application Layer"]
Kestrel[Kestrel Server]
GatewaySvc[GatewayService]
PubsubSvc[PubsubService]
StateSvc[StateService]
end
subgraph Infrastructure["Infrastructure"]
DaprClient[Dapr Client]
ChannelPool[gRPC Channel Pool]
end
subgraph Backend["Backend Services"]
WM[WorkManager<br/>:5002]
RT[WorkManager Runtime<br/>workers, e.g. WebSocketFeed]
end
subgraph Dapr["Dapr Sidecar"]
State[Dapr State]
PubSub[Dapr PubSub]
end
Clients --> ProtocolLayer
ProtocolLayer --> ApplicationLayer
ApplicationLayer --> Infrastructure
Infrastructure --> Backend
Infrastructure --> Dapr
Component Architecture
flowchart LR
subgraph Clients
C[C#]
P[Python]
B[Browser]
end
subgraph Gateway["Virtufin.Api"]
G[gRPC Gateway]
E[Event System]
S[State Service]
end
subgraph Backends
WM[WorkManager]
RT[WorkManager Runtime<br/>workers, e.g. WebSocketFeed]
end
C --> G
P --> G
B --> G
G --> WM
WM --> RT
RT -- publish, state, lease --> G
G <--> S
S <--> State
E <--> PubSub
Component Details
Component Architecture
flowchart TB
subgraph Clients[Clients]
CSharp[C# Client]
Python[Python Client]
Browser[Browser gRPC-Web]
end
subgraph ProtocolLayer[Protocol Layer]
Shared[gRPC + gRPC-Web<br/>gRPC port :5002, HTTP/2]
Probes[Health checks only<br/>HTTP port :5001, HTTP/1.1]
end
subgraph ApplicationLayer[Application Layer]
Kestrel[Kestrel Server]
GatewaySvc[GatewayService gRPC]
ConfigSvc[ConfigService gRPC]
GrpcReflSvc[GrpcReflectionService gRPC]
PubsubSvc[PubsubService]
StateSvc[StateService]
end
subgraph Infrastructure[Infrastructure]
ChannelPool[GrpcChannelPool]
DaprClient[DaprClient]
ConfigLoader[ServicesConfigurationLoader]
end
subgraph Backend[Backend Services]
WM[WorkManager :5002]
RT[WorkManager Runtime<br/>workers, e.g. WebSocketFeed]
end
subgraph Dapr[Dapr Sidecar]
State[Dapr State]
PubSub[Dapr PubSub]
end
Clients --> ProtocolLayer
ProtocolLayer --> ApplicationLayer
ApplicationLayer --> Infrastructure
Infrastructure --> Backend
Infrastructure --> Dapr
System Architecture
flowchart TB
subgraph Clients[Clients]
CSharp[C# Client]
Python[Python Client]
Browser[Browser gRPC-Web]
end
subgraph ProtocolLayer[Protocol Layer]
Shared[gRPC + gRPC-Web<br/>gRPC port :5002, HTTP/2]
Probes[Health checks only<br/>HTTP port :5001, HTTP/1.1]
end
subgraph ApplicationLayer[Application Layer]
Kestrel[Kestrel Server]
GatewaySvc[GatewayService gRPC]
ConfigSvc[ConfigService gRPC]
GrpcReflSvc[GrpcReflectionService gRPC]
PubsubSvc[PubsubService]
StateSvc[StateService]
end
subgraph Infrastructure[Infrastructure]
ChannelPool[GrpcChannelPool]
DaprClient[DaprClient]
ConfigLoader[ServicesConfigurationLoader]
end
subgraph Backend[Backend Services]
WM[WorkManager :5002]
RT[WorkManager Runtime<br/>workers, e.g. WebSocketFeed]
end
subgraph Dapr[Dapr Sidecar]
State[Dapr State]
PubSub[Dapr PubSub]
end
Clients --> ProtocolLayer
ProtocolLayer --> ApplicationLayer
ApplicationLayer --> Infrastructure
Infrastructure --> Backend
Infrastructure --> Dapr
gRPC Invocation
sequenceDiagram
participant Client as C# Client
participant Kestrel as Kestrel
participant Gateway as Gateway Service
participant Pool as GrpcChannel Pool
participant Backend as Backend Service :5002
Client->>Kestrel: gRPC
Kestrel->>Gateway: InvokeRequest
Gateway->>Pool: GetChannel(service)
Pool->>Backend: gRPC Call
Backend-->>Pool: Response
Pool-->>Gateway: InvokeResponse
Gateway-->>Kestrel: InvokeResponse
Kestrel-->>Client: gRPC Response
Event Streaming (Dapr → gRPC)
flowchart LR
Dapr[Dapr Sidecar] --> PubSub[PubSub Event]
PubSub --> Registry[TopicDaprSubscriptionRegistry]
Registry -->|every subscriber| GrpcClient[gRPC Client Subscribe]
Configuration Architecture
flowchart TB
ConfigFile[services.json] --> Loader[ServicesConfigurationLoader]
Loader --> ServicesConfig[ServicesConfiguration]
ServicesConfig --> ChannelPool[GrpcChannelPool]
ServicesConfig --> Reflection[GrpcReflectionService]
ServicesConfig --> PubsubSvc[PubSubService]
ServicesConfig --> State[StateService]
ServicesConfig --> Config[ConfigService]
GrpcChannelPool
Location: Services/GrpcChannelPool.cs
The GrpcChannelPool maintains a thread-safe pool of gRPC channels, one per backend service.
Key Features: - Lazy channel creation (created on first access) - Channel reuse across invocations - LRU eviction when channel limit is reached - Automatic cleanup on application shutdown - Configuration-driven service endpoints
Flow:
sequenceDiagram
participant Client
participant Gateway as GatewayService
participant Pool as GrpcChannelPool
participant Cache as Channel Cache
participant Backend as Backend Service
Client->>Gateway: Invoke(service, method, data)
Gateway->>Pool: GetChannel(serviceName)
Pool->>Cache: Check cached?
Cache-->>Pool: Not found
Pool->>Pool: Create new GrpcChannel
Pool->>Cache: Store in cache
Cache-->>Pool: Channel
Pool-->>Gateway: Channel
Gateway->>Backend: gRPC Call
Backend-->>Gateway: Response
Gateway-->>Client: InvokeResponse
Configuration (services.json):
services:
- name: workmanager
host: localhost
port: 5002
protocol: grpc
GrpcReflectionService
Location: Services/GrpcReflectionService.cs
Provides dynamic service discovery and method invocation using gRPC reflection.
Key Features: - Fetches service descriptors from backend services via reflection - Caches descriptors per service for performance - Uses TypeRegistry for robust JSON↔Protobuf conversion - Handles well-known type descriptors
Class Structure:
| Class | Purpose |
|---|---|
GrpcReflectionService |
Public API, manages cache instances |
ServiceDescriptorCache |
Per-service cache, loads and parses descriptors |
ServiceMethodInfo |
Method metadata (name, input/output types, streaming) |
MethodSchema |
Schema for request/response types |
FieldSchema |
Individual field definitions |
GrpcCallResult |
Invocation result wrapper |
Discovery Flow:
sequenceDiagram
participant Client as GatewayClient
participant Cache as ServiceDescriptorCache
participant Reflection as gRPC Reflection
participant Backend as Backend Service
Client->>Cache: GetMethodsAsync(serviceName)
Cache->>Cache: GetOrCreateCache()
Cache->>Reflection: ServerReflectionInfo()
Reflection->>Backend: ServerReflectionInfo()
Backend-->>Reflection: FileDescriptorProtos
Reflection-->>Cache: Descriptors
Cache->>Cache: Parse and Index
Cache-->>Client: List<MethodInfo>
Invocation Flow:
sequenceDiagram
participant Client
participant Gateway as GatewayService
participant Cache as ServiceDescriptorCache
participant Channel as gRPC Channel
participant Backend as Backend Service
Client->>Gateway: Invoke(request)
Gateway->>Cache: GetOrCreateCache(service)
Cache-->>Gateway: Cached descriptors
Gateway->>Gateway: Create protobuf from JSON
Gateway->>Channel: AsyncUnaryCall()
Channel->>Backend: gRPC Request
Backend-->>Channel: gRPC Response
Channel-->>Gateway: Response bytes
Gateway->>Gateway: Parse to JSON
Gateway-->>Client: GrpcCallResult
Invocation Flow:
flowchart TD
A[ExecuteCallAsync<br/>service, method, json] --> B[GetOrCreateCache<br/>EnsureLoadedAsync]
B --> C[Find method by name]
C --> D[Create protobuf message<br/>from JSON]
D --> E[Create generic<br/>Method byte array byte array]
E --> F[channel.CreateCallInvoker<br/>AsyncUnaryCall]
F --> G[Parse response bytes<br/>to JSON]
G --> H[Return GrpcCallResult]
GatewayService
Location: Services/GatewayService.cs
The main gRPC service implementing the Gateway protocol.
gRPC Methods:
| Method | Type | Description |
|---|---|---|
Invoke |
Unary | Invoke a method on a backend service |
ListServices |
Unary | List all registered services |
ListMethods |
Unary | List methods for a service |
Subscribe |
Server Streaming | Subscribe to events |
Invoke Flow:
flowchart TD
A[Client calls<br/>Gateway.Invoke<br/>InvokeRequest] --> B[Extract request headers<br/>as metadata]
B --> C[Call ReflectionService<br/>ExecuteCallAsync]
C --> D[Map result to<br/>InvokeResponse]
D --> E[Return to client]
PubsubService
Location: Services/PubsubService.cs
Implements the Pubsub gRPC service: PublishEvent, PublishEvents, Subscribe,
ListTopics and ChangePublicationFence. Canceling Subscribe unsubscribes.
Subscriptions are filtered by topic only — there is no scope hierarchy, no service
filter, and no event-type filter. A subscriber that needs finer granularity inspects
cloudevent.type itself.
Subscribe creates one bounded buffer (SubscriberBuffer, 1024 events) per call, shared
across all topics named in that call, and multiplexes every topic's events into the single
response stream. The bound counts events, so a whole batch (see
The form of an event on its way) takes the room of the
events it holds.
A consumer that falls further behind than the bound holds nobody back: the gateway
serves it from the topic's stream at its own pace and puts it back on live delivery when
it has caught up (see Subscribers that are behind).
Response headers are flushed before any event is written. Request-reply clients depend on this to know the subscription is live before they publish — without it, a client waits for metadata that cannot arrive until it publishes, and won't publish until metadata arrives.
A call with
announce_livealso gets a firstSubscribeResponsewithlive = true(no topic, no event) right after the headers. It is for clients that cannot see headers before the first body bytes: Firefox'sfetch()resolves only then, so the web app over gRPC-Web learns that a quiet subscription is live only from this response.
TopicDaprSubscriptionRegistry
Location: Services/TopicDaprSubscriptionRegistry.cs
The in-process fan-out broker. Holds one shared Dapr streaming subscription per topic per process and the set of subscribers (each Subscribe call's buffer) on it; the set is the reference count. Dapr pub/sub is competing-consumer: a subscription per caller would make daprd load-balance each event across callers instead of delivering it to all of them, so callers share one and the registry writes every message to every subscriber.
The subscription opens with the first subscriber and closes with the last. It runs on its
own token, so the subscriber that opened it may leave first. If it ends on its own (the
sidecar stream faulted), every subscriber's stream ends with Unavailable and the next
Subscribe opens a fresh one.
sequenceDiagram
participant Client
participant Pubsub as PubsubService
participant Registry as TopicDaprSubscriptionRegistry
participant Dapr as Dapr Sidecar
Client->>Pubsub: Subscribe(topics)
Pubsub->>Registry: AcquireAsync(topic, buffer, acceptBatches)
alt first subscriber for this topic
Registry->>Dapr: SubscribeAsync(pubsub, topic, handler)
else topic already subscribed
Registry->>Registry: add subscriber
end
Pubsub->>Client: flush response headers
opt announce_live
Pubsub->>Client: SubscribeResponse(live = true)
end
Dapr->>Registry: TopicMessage
Registry->>Client: SubscribeResponse (to every subscriber)
Client->>Pubsub: cancel call
Pubsub->>Registry: dispose handle (remove subscriber)
Registry->>Dapr: dispose subscription when the last subscriber leaves
SubscriptionHealthSweeperHostedService
Location: Services/SubscriptionHealthSweeperHostedService.cs
Every minute, writes a heartbeat to each subscriber's buffer and ends the call of a
subscriber whose full buffer took no write for PubsubSubscriberStallSeconds (default
300): its client is gone or stuck. The last one leaving closes the Dapr subscription. A
subscriber that is merely behind, with a full buffer it keeps reading from, stays.
The form of an event on its way
Location: Services/CloudEventExtensions.cs, Services/PubsubBatchEntry.cs,
Services/SubscribedCloudEvents.cs
An event is a protobuf CloudEvent on every leg: in the publisher's request, in the
topic's stream and in the subscriber's response. It is never turned into another format
on the way, so its data and its attributes arrive as they were sent, and the gateway
spends no time on a conversion. (The one change is a time sent as a string, which is
stored as a timestamp.)
The events one PublishEvents call sends for a topic are stored together, as one stream
entry. What the gateway does with such an entry depends on the subscriber:
flowchart TD
Pub["Publisher<br/>PublishEvents (protobuf CloudEvents)"] --> Store["Gateway<br/>one stream entry per topic:<br/>an encoded CloudEventBatch"]
Store --> Stream[("Topic stream")]
Stream --> Deliver["Gateway<br/>delivery"]
Deliver -->|default| Single["Unpack the entry:<br/>one SubscribeResponse per event<br/>(cloudevent)"]
Deliver -->|accept_batches| Whole["Forward the stored bytes:<br/>one SubscribeResponse per entry<br/>(batch)"]
Single --> ClientA["Client wrappers, app, TUI"]
Whole --> ClientB["WorkManager Runtime"]
- Default. The gateway unpacks the entry and sends one response per event. Every client wrapper works this way.
- Whole batches. For a subscriber that set
accept_batches, the gateway counts the entry's events from its framing and forwards the bytes. It reads no event, and the subscriber cuts the events out where it needs them. This removes the gateway's remaining cost per event for a bulk consumer. - Both kinds of subscriber can share a topic. Each shape is built at most once per entry, and only when a subscriber needs it.
- An entry that is no protobuf CloudEvent can only come from a writer other than the
gateway. It is delivered as an event of type
unknownrather than being lost.
Subscribers that are behind
Location: Services/TopicDaprSubscriptionRegistry.CatchUp.cs
The gateway's handler of a topic must answer Dapr at once. Dapr's Redis component has one queue and ten workers per sidecar for all its subscriptions, so a handler that waits for one slow subscriber stalls every other topic of the pod (measured: a marker topic fell to 12 events/s next to a consumer that was behind). Dropping the slow subscriber's events instead loses data silently. So delivery does neither: a subscriber whose buffer cannot take an entry gets a read position of its own.
sequenceDiagram
participant Dapr as daprd
participant Live as Live delivery (handler)
participant Reader as Catch-up reader
participant Sub as Subscriber buffer
Dapr->>Live: entry
Live--xSub: buffer full
Live->>Reader: start (rest of the entry, sidecar position, pending entries)
Live-->>Dapr: Success (at once)
loop until the stream's end
Reader->>Sub: entries from the stream, waiting for room
end
Reader->>Live: hand over under the topic's gate (entries live delivery still brings)
Dapr->>Live: next entry
Live->>Sub: live again
- One gate per topic. Live delivery of an entry and a reader's handover run under it, so the sidecar's position, its pending entries and the entries handled so far describe one moment. Live delivery only ever writes without waiting.
- What the reader gives. The rest of the entry that did not fit; the entries the sidecar had read but live delivery had not handled; then everything after the sidecar's position, in the stream's order.
- The handover. At the stream's end the reader takes the gate, reads the sidecar's position once more and tells live delivery which of the entries it gave are still to come (those after that position, and the pending ones not handled yet). Live delivery passes the subscriber over for each of them once.
- Errors go toward duplicates. Entries are recognized by CloudEvent
sourceandid. An entry without a usable id is never passed over, so it may arrive twice, never not at all. - A gap is said, not hidden. A stream trims from its start. When the entry the reader
stands at is gone and newer ones exist, events are missing: the call ends with
DATA_LOSS. The subscriber decides what a gap means for it; WorkManager's Runtime subscribes again and tells the worker. - Bounded cost. A reader holds one read of about 1 MiB and the subscriber's buffer;
a subscriber that takes nothing for
PubsubSubscriberStallSecondshas its call ended.
Only the Redis backend has a stream to read from today. On other backends a subscriber
whose buffer is full has its call ended with RESOURCE_EXHAUSTED and subscribes again.
Paced publishing
Location: Services/ConsumerProgress.cs, Services/ConsumerProgressListener.cs
A subscriber that is behind is served from the stream, but only as far back as the stream
reaches (streamTTL). Live data cannot wait for it, so there a gap is the honest outcome.
A source that can wait has no reason to lose events, so it can ask to be paced: the
gateway holds its PublishEvents call while a consumer of the topic is behind by half the
retention or more. The same rule applies to every topic. Simulation and live differ only
by their topics, never by how the gateway treats them.
sequenceDiagram
participant Src as Paced publisher
participant GW as Gateway pod
participant Topic as sys.api.pubsub.progress.reported
participant RT as Runtime (consumer)
RT->>GW: ReportProgress(worker/w, hyp.t, position)
GW->>Topic: one event per call
Topic-->>GW: every pod applies it
Src->>GW: PublishEvents(pace)
Note over GW: worker/w lags >= high-water mark: hold
RT->>GW: ReportProgress(position moved)
GW-->>Src: published
- Positions are times. A position is at or before the stream entry of the last event the consumer finished. Retention is a time too, so a consumer whose lag stays under it loses nothing. No stream ids are needed, and the rule works on any pub/sub backend.
- Every pod knows every consumer. A report is applied on the pod that takes it and
published once on the gateway's progress topic. Each pod has its own consumer group,
so every pod applies every report, whichever pod a consumer reports through. A held
publish wakes on each report, and also every
PubsubPaceRecheckSeconds, because leases and stalls run out without a report. - Idle is not behind. On a quiet topic a consumer's position grows old although
nothing waits for it. A consumer reports
idle, and then it does not count. - Nothing waits forever.
- A consumer that stops reporting stops counting after its lease.
- One that keeps reporting the same position while not idle stops counting after
PubsubProgressStallSeconds, and the gateway logs it. - A held call ends with
RESOURCE_EXHAUSTEDafterPubsubPaceMaxWaitSeconds, with nothing published. - A publisher's own positions never hold back its own call, so a cycle of workers cannot hold itself.
- Delivery is untouched. A held call is the publisher's own unary call. It holds no subscription handler, so other topics and subscribers are served as before.
Prior art: Apache Pulsar's backlog quota with the producer_request_hold policy holds
producers while a subscription's backlog is over a quota. This gateway does the same,
measured in time instead of size.
DaprAppCallbackService
Location: Services/DaprAppCallbackService.cs
Receives Dapr Scheduler job callbacks and publishes an empty CloudEvent to the job's
target_topic. Bound on both Dapr's alpha and stable AppCallback routes —
DaprStableAppCallbackMethodProvider adds the stable one, which the .NET SDK does not
generate. Because subscriptions are created programmatically rather than declared, the
ListTopicSubscriptions callback deliberately returns an empty list.
Data Flow Diagrams
gRPC Invocation
sequenceDiagram
participant Client as C# Client
participant Kestrel as Kestrel
participant Gateway as Gateway Service
participant Pool as GrpcChannel Pool
participant Backend as Backend Service :5002
Client->>Kestrel: gRPC
Kestrel->>Gateway: InvokeRequest
Gateway->>Pool: GetChannel(service)
Pool->>Backend: gRPC Call
Backend-->>Pool: Response
Pool-->>Gateway: InvokeResponse
Gateway-->>Kestrel: InvokeResponse
Kestrel-->>Client: gRPC Response
Event Streaming (Dapr → gRPC)
flowchart LR
Dapr[Dapr Sidecar] -->|Pub/Sub| Registry[TopicDaprSubscriptionRegistry]
Registry -->|every subscriber| GrpcClient[gRPC Client Subscribe]
Configuration Architecture
flowchart TB
ConfigFile[services.json] --> Loader[ServicesConfigurationLoader]
Loader --> ServicesConfig[ServicesConfiguration]
ServicesConfig --> ChannelPool[GrpcChannelPool]
ServicesConfig --> Gateway[GatewayService]
ServicesConfig --> Reflection[AggregatedReflectionService]
ServicesConfig --> State["StateService<br/>(store name only)"]
ServicesConfig --> Config[ConfigService]
Health Checks
| Check | Name | Healthy when | On /ready |
|---|---|---|---|
DaprHealthCheck |
dapr |
Dapr sidecar is reachable | yes |
GrpcChannelPoolHealthCheck |
grpc-channel-pool |
Channel pool has channels for the configured services | yes |
GatewayCircuitBreakerHealthCheck |
dapr-circuit-breaker |
The gateway circuit breaker is not open | no |
ApiAuthHealthCheck |
api-auth |
API-key auth is configured as expected | yes |
/health and /healthz are the liveness probe: they run no check and answer as long as the
process does, because no failing dependency is fixed by restarting the gateway (a restart drops
every subscription). /ready is the readiness probe and runs the checks marked above. The
circuit breaker is left out: it opens when a backend fails, and an open breaker already fails
calls at once with a clear error; taking the gateway out of its Service on top of that turned a
backend that was slow to start into "connection refused" for every caller (2026-11-14).
A gRPC health service is also mapped at grpc.health.v1.Health and reports all four checks
(the TUI watches it); the API-key interceptor exempts it from authentication.