Skip to content

Publish and subscribe

Publish a CloudEvent and subscribe to a topic from each client library. The wire type, topics and delivery rules are in Events.

Client examples

C#

using var client = new ApiClient("localhost");

var ce = new CloudEvent
{
    Id = Guid.NewGuid().ToString(),
    Source = "urn:virtufin:my-service",
    SpecVersion = "1.0",
    Type = "com.virtufin.worker.started",
    TextData = """{"workerId":"abc123"}""",
};
await client.Gateway.PublishEventAsync("workmanager.lifecycle", ce);

await using var sub = await client.SubscribeAsync(["workmanager.lifecycle"], token);
await foreach (var evt in sub)
    Console.WriteLine($"{evt.Topic}: {evt.Cloudevent.Type}");

Python

async with ApiClient(host="localhost") as client:
    ce = cloudevents_pb2.CloudEvent(
        id=str(uuid.uuid4()),
        source="urn:virtufin:my-service",
        spec_version="1.0",
        type="com.virtufin.worker.started",
        text_data=json.dumps({"workerId": "abc123"}),
    )
    await client.pubsub.publish_async("workmanager.lifecycle", ce)

    call = await client.pubsub.subscribe_async(topics=["workmanager.lifecycle"])
    async for event in call:
        print(event.topic, event.cloudevent.type)

TypeScript

const client = new ApiClient({ host: "localhost" });

await client.publish("workmanager.lifecycle", cloudevent);

const sub = await client.subscribe(["workmanager.lifecycle"]);
for await (const evt of sub) {
  console.log(evt.topic, evt.cloudevent?.type);
}

Best practices

  1. Name your topics explicitly on Subscribe — the empty-list default is sys.api.state.saved/deleted, which is almost never what you want.
  2. Handle a failed publish as an error: it is a non-OK gRPC status whose ErrorInfo names the reason (Errors).
  3. Pass a cancellation token to Subscribe and cancel it to tear down; that is the only working teardown path.
  4. Discriminate on cloudevent.type, not on the topic alone — one topic carries a service's whole event taxonomy.
  5. Leave include_value off unless the state value is public to the whole platform.
  6. Use the SDK's request-reply helper instead of hand-rolling correlation.