Declarative, streaming, and programmatic subscription types

Learn more about the subscription types that allow you to subscribe to message topics.

Pub/sub API subscription types

Dapr applications can subscribe to published topics via three subscription types that support the same features: declarative, streaming and programmatic.

Subscription typeDescription
DeclarativeSubscription is defined in an external file. The declarative approach removes the Dapr dependency from your code and allows for existing applications to subscribe to topics, without having to change code.
StreamingSubscription is defined in the application code. Streaming subscriptions are dynamic, meaning they allow for adding or removing subscriptions at runtime. They do not require a subscription endpoint in your application (that is required by both programmatic and declarative subscriptions), making them easy to configure in code. Streaming subscriptions also do not require an app to be configured with the sidecar to receive messages.
ProgrammaticSubscription is defined in the application code. The programmatic approach implements the static subscription and requires an endpoint in your code.

The examples below demonstrate pub/sub messaging between a checkout app and an orderprocessing app via the orders topic. The examples demonstrate the same Dapr pub/sub component used first declaratively, then programmatically.

Declarative subscriptions

Note

This feature is currently in preview. Dapr can be made to “hot reload” declarative subscriptions, whereby updates are picked up automatically without needing a restart. This is enabled by via the HotReload feature gate. To prevent reprocessing or loss of unprocessed messages, in-flight messages between Dapr and your application are unaffected during hot reload events.

You can subscribe declaratively to a topic using an external component file. This example uses a YAML component file named subscription.yaml:

  1. apiVersion: dapr.io/v2alpha1
  2. kind: Subscription
  3. metadata:
  4. name: order
  5. spec:
  6. topic: orders
  7. routes:
  8. default: /checkout
  9. pubsubname: pubsub
  10. scopes:
  11. - orderprocessing
  12. - checkout

Here the subscription called order:

  • Uses the pub/sub component called pubsub to subscribes to the topic called orders.
  • Sets the route field to send all topic messages to the /checkout endpoint in the app.
  • Sets scopes field to scope this subscription for access only by apps with IDs orderprocessing and checkout.

When running Dapr, set the YAML component file path to point Dapr to the component.

  1. dapr run --app-id myapp --resources-path ./myComponents -- dotnet run
  1. dapr run --app-id myapp --resources-path ./myComponents -- mvn spring-boot:run
  1. dapr run --app-id myapp --resources-path ./myComponents -- python3 app.py
  1. dapr run --app-id myapp --resources-path ./myComponents -- npm start
  1. dapr run --app-id myapp --resources-path ./myComponents -- go run app.go

In Kubernetes, apply the component to the cluster:

  1. kubectl apply -f subscription.yaml

In your application code, subscribe to the topic specified in the Dapr pub/sub component.

  1. //Subscribe to a topic
  2. [HttpPost("checkout")]
  3. public void getCheckout([FromBody] int orderId)
  4. {
  5. Console.WriteLine("Subscriber received : " + orderId);
  6. }
  1. import io.dapr.client.domain.CloudEvent;
  2. //Subscribe to a topic
  3. @PostMapping(path = "/checkout")
  4. public Mono<Void> getCheckout(@RequestBody(required = false) CloudEvent<String> cloudEvent) {
  5. return Mono.fromRunnable(() -> {
  6. try {
  7. log.info("Subscriber received: " + cloudEvent.getData());
  8. }
  9. });
  10. }
  1. from cloudevents.sdk.event import v1
  2. #Subscribe to a topic
  3. @app.route('/checkout', methods=['POST'])
  4. def checkout(event: v1.Event) -> None:
  5. data = json.loads(event.Data())
  6. logging.info('Subscriber received: ' + str(data))
  1. const express = require('express')
  2. const bodyParser = require('body-parser')
  3. const app = express()
  4. app.use(bodyParser.json({ type: 'application/*+json' }));
  5. // listen to the declarative route
  6. app.post('/checkout', (req, res) => {
  7. console.log(req.body);
  8. res.sendStatus(200);
  9. });
  1. //Subscribe to a topic
  2. var sub = &common.Subscription{
  3. PubsubName: "pubsub",
  4. Topic: "orders",
  5. Route: "/checkout",
  6. }
  7. func eventHandler(ctx context.Context, e *common.TopicEvent) (retry bool, err error) {
  8. log.Printf("Subscriber received: %s", e.Data)
  9. return false, nil
  10. }

The /checkout endpoint matches the route defined in the subscriptions and this is where Dapr sends all topic messages to.

Streaming subscriptions

Streaming subscriptions are subscriptions defined in application code that can be dynamically stopped and started at runtime. Messages are pulled by the application from Dapr. This means no endpoint is needed to subscribe to a topic, and it’s possible to subscribe without any app configured on the sidecar at all. Any number of pubsubs and topics can be subscribed to at once. As messages are sent to the given message handler code, there is no concept of routes or bulk subscriptions.

Note: Only a single pubsub/topic pair per application may be subscribed at a time.

The example below shows the different ways to stream subscribe to a topic.

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/dapr/go-sdk/client"
  6. )
  7. func main() {
  8. cl, err := client.NewClient()
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. sub, err := cl.Subscribe(context.Background(), client.SubscriptionOptions{
  13. PubsubName: "pubsub",
  14. Topic: "orders",
  15. })
  16. if err != nil {
  17. panic(err)
  18. }
  19. // Close must always be called.
  20. defer sub.Close()
  21. for {
  22. msg, err := sub.Receive()
  23. if err != nil {
  24. panic(err)
  25. }
  26. // Process the event
  27. // We _MUST_ always signal the result of processing the message, else the
  28. // message will not be considered as processed and will be redelivered or
  29. // dead lettered.
  30. // msg.Retry()
  31. // msg.Drop()
  32. if err := msg.Success(); err != nil {
  33. panic(err)
  34. }
  35. }
  36. }

or

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/dapr/go-sdk/client"
  6. "github.com/dapr/go-sdk/service/common"
  7. )
  8. func main() {
  9. cl, err := client.NewClient()
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. stop, err := cl.SubscribeWithHandler(context.Background(),
  14. client.SubscriptionOptions{
  15. PubsubName: "pubsub",
  16. Topic: "orders",
  17. },
  18. eventHandler,
  19. )
  20. if err != nil {
  21. panic(err)
  22. }
  23. // Stop must always be called.
  24. defer stop()
  25. <-make(chan struct{})
  26. }
  27. func eventHandler(e *common.TopicEvent) common.SubscriptionResponseStatus {
  28. // Process message here
  29. // common.SubscriptionResponseStatusRetry
  30. // common.SubscriptionResponseStatusDrop
  31. common.SubscriptionResponseStatusDrop, status)
  32. }
  33. return common.SubscriptionResponseStatusSuccess
  34. }

Demo

Watch this video for an overview on streaming subscriptions:

Programmatic subscriptions

The dynamic programmatic approach returns the routes JSON structure within the code, unlike the declarative approach’s route YAML structure.

Note: Programmatic subscriptions are only read once during application start-up. You cannot dynamically add new programmatic subscriptions, only at new ones at compile time.

In the example below, you define the values found in the declarative YAML subscription above within the application code.

  1. [Topic("pubsub", "orders")]
  2. [HttpPost("/checkout")]
  3. public async Task<ActionResult<Order>>Checkout(Order order, [FromServices] DaprClient daprClient)
  4. {
  5. // Logic
  6. return order;
  7. }

or

  1. // Dapr subscription in [Topic] routes orders topic to this route
  2. app.MapPost("/checkout", [Topic("pubsub", "orders")] (Order order) => {
  3. Console.WriteLine("Subscriber received : " + order);
  4. return Results.Ok(order);
  5. });

Both of the handlers defined above also need to be mapped to configure the dapr/subscribe endpoint. This is done in the application startup code while defining endpoints.

  1. app.UseEndpoints(endpoints =>
  2. {
  3. endpoints.MapSubscribeHandler();
  4. });
  1. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  2. @Topic(name = "checkout", pubsubName = "pubsub")
  3. @PostMapping(path = "/orders")
  4. public Mono<Void> handleMessage(@RequestBody(required = false) CloudEvent<String> cloudEvent) {
  5. return Mono.fromRunnable(() -> {
  6. try {
  7. System.out.println("Subscriber received: " + cloudEvent.getData());
  8. System.out.println("Subscriber received: " + OBJECT_MAPPER.writeValueAsString(cloudEvent));
  9. } catch (Exception e) {
  10. throw new RuntimeException(e);
  11. }
  12. });
  1. @app.route('/dapr/subscribe', methods=['GET'])
  2. def subscribe():
  3. subscriptions = [
  4. {
  5. 'pubsubname': 'pubsub',
  6. 'topic': 'checkout',
  7. 'routes': {
  8. 'rules': [
  9. {
  10. 'match': 'event.type == "order"',
  11. 'path': '/orders'
  12. },
  13. ],
  14. 'default': '/orders'
  15. }
  16. }]
  17. return jsonify(subscriptions)
  18. @app.route('/orders', methods=['POST'])
  19. def ds_subscriber():
  20. print(request.json, flush=True)
  21. return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
  22. app.run()
  1. const express = require('express')
  2. const bodyParser = require('body-parser')
  3. const app = express()
  4. app.use(bodyParser.json({ type: 'application/*+json' }));
  5. const port = 3000
  6. app.get('/dapr/subscribe', (req, res) => {
  7. res.json([
  8. {
  9. pubsubname: "pubsub",
  10. topic: "checkout",
  11. routes: {
  12. rules: [
  13. {
  14. match: 'event.type == "order"',
  15. path: '/orders'
  16. },
  17. ],
  18. default: '/products'
  19. }
  20. }
  21. ]);
  22. })
  23. app.post('/orders', (req, res) => {
  24. console.log(req.body);
  25. res.sendStatus(200);
  26. });
  27. app.listen(port, () => console.log(`consumer app listening on port ${port}!`))
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "github.com/gorilla/mux"
  8. )
  9. const appPort = 3000
  10. type subscription struct {
  11. PubsubName string `json:"pubsubname"`
  12. Topic string `json:"topic"`
  13. Metadata map[string]string `json:"metadata,omitempty"`
  14. Routes routes `json:"routes"`
  15. }
  16. type routes struct {
  17. Rules []rule `json:"rules,omitempty"`
  18. Default string `json:"default,omitempty"`
  19. }
  20. type rule struct {
  21. Match string `json:"match"`
  22. Path string `json:"path"`
  23. }
  24. // This handles /dapr/subscribe
  25. func configureSubscribeHandler(w http.ResponseWriter, _ *http.Request) {
  26. t := []subscription{
  27. {
  28. PubsubName: "pubsub",
  29. Topic: "checkout",
  30. Routes: routes{
  31. Rules: []rule{
  32. {
  33. Match: `event.type == "order"`,
  34. Path: "/orders",
  35. },
  36. },
  37. Default: "/orders",
  38. },
  39. },
  40. }
  41. w.WriteHeader(http.StatusOK)
  42. json.NewEncoder(w).Encode(t)
  43. }
  44. func main() {
  45. router := mux.NewRouter().StrictSlash(true)
  46. router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET")
  47. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", appPort), router))
  48. }

Next Steps

Last modified October 11, 2024: Fixed typo (#4389) (fe17926)