concept event in category microservice

appears as: event, events, An event, events, n event, event, The event, The Event, The events
Microservices in .NET Core, Second Edition

This is an excerpt from Manning's book Microservices in .NET Core, Second Edition.

Figure 1.8. When a user adds an item to their shopping cart, the front end makes a request to the API Gateway microservice, which collaborates with other microservices to fulfill the request. During processing, microservices may raise events that other microservices can subscribe to and handle asynchronously.
ch01 fig 08 horsdal2

Each microservice implements a single capability; but to deliver end user functionality, microservices need to collaborate. Microservices can use three main communication styles for collaboration: commands, queries, and events. Each style has its strengths and weaknesses, and understanding the trade-offs between them allows you to pick the appropriate one for each microservice collaboration. When you get the collaboration style right, you can implement loosely coupled microservices with clear boundaries.

  • Events —Events are used when a microservice needs to react to something that happened in another microservice. The Loyalty Program microservice subscribes to events from the Special Offers microservice so that when a new special offer is made available, it can have notifications sent to registered users.
  • The collaboration between two microservices can use one, two, or all three of these collaboration styles. Each time two microservices need to collaborate, you must decide which style to use. Figure 5.2 shows the collaborations of Loyalty Program again, but this time identifying the collaboration style I chose for each one.

    Figure 5.2. The Loyalty Program microservice uses all three collaboration styles: commands, queries, and events.
    ch05 fig 2 horsdal2

    Collaboration based on commands and queries should use relatively coarse-grained commands and queries. The calls made between microservices are remote calls, meaning they cross at least a process boundary and usually also a network. This means calls between microservices are relatively slow. Even though the microservices are fine grained, you must not fall into the trap of thinking of calls from one microservice to another as being like function calls in a microservice.

    The response to this request also uses YAML:

    HTTP/1.1 201 Created
    Content-Type: application/yaml                 #1
    Location: http://localhost:5000/users/1
    
    Id: 1                                         #2
    Name: Christian
    Settings:
      Interests:
      - whisky
      - cycling
      - "software design"
    Microservices Security in Action

    This is an excerpt from Manning's book Microservices Security in Action.

    There are two common methods. One approach is to poll the PAP continuously after a set period and then pull new and updated policies from PAP. The other approach is based on a push mechanism. Whenever a new policy or policy update is available, the PAP publishes an event to a topic (see figure 1.13). Each microservice acts as an event consumer and registers for the events it’s interested in. Whenever a microservice receives an event for a registered topic, it pulls the corresponding policy from the PAP and updates the embedded PDP.

    In this section, we discuss the need to have reactive microservices in your microservices deployment. A microservice is considered to be reactive when it can react to events that occur in a system without explicitly being called by the event originator; the recipient microservice is decoupled from the calling microservice. The microservice that generates events doesn’t necessarily need to know which microservices consume those events.

    Figure 9.1 The Order Processing microservice talks to other microservices to initiate events related to processing an order, such as paying for the order, updating the inventory, and so on.
    events {}
    http {
        server {
            listen 8080;
            location / {
                proxy_pass         http://socat:2345/;
                proxy_redirect     off;
                proxy_set_header   Host $host;
                proxy_set_header   X-Real-IP $remote_addr;
                proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Host $server_name;
            }
        }
    }
    Microservices in Action

    This is an excerpt from Manning's book Microservices in Action.

    It’s interesting to think about how decoupling functionality in the online investment system helps you be more flexible in the face of changing requirements. Imagine that you need to change how fees are calculated. You could make and release those changes to the fees service without any change to its upstream or downstream services. Or imagine an entirely new requirement: when an order is placed, you need to alert your risk team if it doesn’t match normal trading patterns. It’d be easy to build a new microservice to perform that operation based on an event raised by the orders service without changing the rest of the system.

  • In event sourcing, you’d store the events that happened to change the state of the order. You could materialize the current state of the order by replaying those events.
  • Figure 5.13 A service storing state in a data store and publishing events, in two distinct actions

    c05_13.png

    Figure 5.14 An order, stored as a sequence of events

    c05_14.png

    Figure 5.14 illustrates the event sourcing approach for tracking an order’s history.

    This architecture solves a common problem in enterprise applications: understanding how you reached your current state. It removes the division between state and events; you don’t need to stick events on top of your business logic, because your business logic inherently generates and manipulates events. On the other hand, it makes complex queries more difficult: you’d need to materialize views to perform joins or filter by field values, as your event storage format would only support retrieving entities by their primary key.

    Event sourcing isn’t a requirement for a microservice application, but using events to store application state can be a particularly elegant tool, especially for applications involving complex sagas where tracking the history of state transitions is vital. If you’re interested in learning more about event sourcing, Nick Chamberlain’s awesome-ddd list (https://github.com/heynickc/awesome-ddd) has a great collection of resources and further reading.

    Listing 7.2 microservices-in-action/chapter-7/chassis/events_demo.py
    from nameko.events import EventDispatcher, event_handler
    from nameko.rpc import rpc
    from nameko.timer import timer
    
    class EventPublisherService:
     name = "publisher_service"    #1  
     dispatch = EventDispatcher()  #2  
    
        @rpc
        def publish(self, event_type, payload):
            self.dispatch(event_type, payload)
    
    class AnEventListenerService:
     name = "an_event_listener_service"    #1  
     @event_handler("publisher_service", "an_event")    #3  
        def consume_an_event(self, payload):
            print("service {} received:".format(self.name), payload)
    
    class AnotherEventListenerService:
        name = "another_event_listener_service"
    
        @event_handler("publisher_service", "another_event")
        def consume_another_event(self, payload):
            print("service {} received:".format(self.name), payload)
    
    class ListenBothEventsService:
     name = "listen_both_events_service"    #1  
     @event_handler("publisher_service", "an_event")    #3  
        def consume_an_event(self, payload):
            print("service {} received:".format(self.name), payload)
     @event_handler("publisher_service", "another_event")    #3  
        def consume_another_event(self, payload):
            print("service {} received:".format(self.name), payload)
    
    #1   Registers the service name, which allows you to refer to it on other services
    #2   Allows this service to create events that’ll be routed to a queue in RabbitMQ
    #3   By using this annotation, ListenBothEventsService will execute the function when the publisher service issues an event. The first argument of the annotation is the name of the service whose events will be listened to, and the second argument of the annotation is the name of the event.
    Spring Microservices in Action

    This is an excerpt from Manning's book Spring Microservices in Action.

  • Scalable— How do you use asynchronous processing and events to minimize the direct dependencies between your services and ensure that you can gracefully scale your microservices?
  • This chapter is about how to design and implement your Spring-based microservices to communicate with other microservices using asynchronous messages. Using asynchronous messages to communicate between applications isn’t new. What’s new is the concept of using messages to communicate events representing changes in state. This concept is called Event Driven Architecture (EDA). It’s also known as Message Driven Architecture (MDA). What an EDA-based approach allows you to do is to build highly decoupled systems that can react to changes without being tightly coupled to specific libraries or services. When combined with microservices, EDA allows you to quickly add new functionality into your application by merely having the service listen to the stream of events (messages) being emitted by your application.

    package com.thoughtmechanix.licenses;
    //Imports removed for conciseness
    @EnableBinding(Sink.class)                                               #1
    public class Application {     
       //Code removed for conciseness
        @StreamListener(Sink.INPUT)                                          #2
        public void loggerSink(
           OrganizationChangeModel orgChange) {
           logger.debug("Received an event for organization id {}" , orgChange.getOrganizationId());
        }
    }
    Microservices in .NET Core: with examples in Nancy

    This is an excerpt from Manning's book Microservices in .NET Core: with examples in Nancy.

    Figure 1.7. The Shopping Cart microservice publishes events, and other subscribing microservices react.

    The trigger for these side effects is an ItemAddedToShoppingCart event published by the Shopping Cart microservice. Two other microservices subscribe to events from Shopping Cart and take the necessary actions as events (such as ItemAddedToShoppingCart events) occur. These two subscribers react to the events asynchronously—outside the context of the original request—so the side effects may happen in parallel with the main handling of the request or after the main handling has completed.

    Let’s consider an example. The Shopping Cart microservice publishes events every time an item is added to or removed from a shopping cart. Figure 5.5 shows a Shopper Tracking microservice that subscribes to those events and updates a read model based on the events. Shopper Tracking allows business users to query how many times specific items are added to or removed from shopping carts.

    Figure 5.5. The Shopper Tracking microservice subscribes to events from the Shopping Cart microservice and keeps track of how many times products are added to or removed from shopping carts.

    The events published from the Shopping Cart microservice aren’t in themselves an efficient model to query when you want to find out how often a product has been added to or removed from shopping carts. But the events are a good source from which to build such a model. The Shopper Tracking microservice keeps two counters for every product: one for how many times the product has been added to a shopping cart, and one for how many times it’s been removed. Every time an event is received from Shopping Cart, one of the counters is updated; and every time a query is made about a product, the two counters for that product are read.

    5.3.2. Storing events raised by a microservice

    This section looks at storing the events raised by a microservice. During command processing, a microservice can decide to raise events. Figure 5.7 shows the standard set of components in a microservice: the domain model raises the events. It typically does so when there’s a change or a set of changes to the state of the data for which the microservice is responsible.

    Figure 5.7. The components in the Shopping Cart microservice involved in raising and saving events are the Shopping Cart domain model, the EventStore component, and the Event Store database.

    The events should reflect a change to the state of the data owned by the microservice. The events should also make sense in terms of the capability implemented by the microservice. For example, in a Shopping Cart microservice, when a user has added an item to their shopping cart, the event raised is ItemAddedToShoppingCart, not RowAddedToShoppingCartTable. The difference is that the first signifies an event of significance to the system—a user did something that’s interesting in terms of the business—whereas the latter would report on a technical detail—a piece of software did something because a programmer decided to implement it that way. The events should be of significance at the level of abstraction of the capability implemented by the microservice, and they will often cover several updates to the underlying database. The events should correspond to business-level transactions, not to database transactions.

    Whenever the domain logic in a microservice raises an event, it’s stored to the event store in the microservice. In figure 5.8, this is done through the EventStore component, which is responsible for talking to the database where the events are stored.

    Figure 5.8. When the domain model raises an event, the EventStore component code must write it to the Event Store database.

    The following two sections show two implementations of an EventStore component. The first stores the events by hand to a table in a SQL database, and the second uses the open source Event Store database.

    Before we dive into implementing the EventStore component, here’s a reminder of what the Event type in Shopping Cart looks like:

    public struct Event
    {
      public long SequenceNumber { get; }
      public DateTimeOffset OccurredAt { get; }
      public string Name { get; }
      public object Content { get; }
    
      public Event(
        long sequenceNumber,
        DateTimeOffset occurredAt,
        string name,
        object content)
      {
        this.SequenceNumber = sequenceNumber;
        this.OccurredAt = occurredAt;
        this.Name = name;
        this.Content = content;
      }
    }

    It’s events of this type that you’ll store in the event store database. The first step is to go into the ShoppingCart database and add a table like the one shown in figure 5.9. The database script in Chapter05\ShoppingCart\src\database-scripts\create-shopping-cart-db.sql in the code download creates this table, along with the other two tables in the ShoppingCart database.

    Figure 5.9. The EventStore table has four columns for these categories: event ID, event name, the time the event occurred, and the contents of the event.

    Next, add a file named EventStore.cs to Shopping Cart, and add to it the following code for writing events.

    Example 5.3. Raising an event, which amounts to storing it

    This code doesn’t compile yet, because the IEventStore interface has another method: one for reading events. That side is implemented as shown next.