commandbus | Command Bus Pattern in Python
kandi X-RAY | commandbus Summary
kandi X-RAY | commandbus Summary
Command bus is a pattern from CQRS. In this pattern we have three components:.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Publish a command .
- Subscribes a command .
- Initialize the session .
commandbus Key Features
commandbus Examples and Code Snippets
Community Discussions
Trending Discussions on commandbus
QUESTION
Suppose I want to make an e-commerce system. I have 2 aggregates here ProductAggregate and UserAggregate. Product aggregate contains productId, price. User aggregate contains userId and balance. Here's the problem, in event-sourcing we should not rely on the read model since there might be eventual consistency problem. Ok so we should rely on the command model right I guess?, but this two command model is different. I read from somewhere else they told me that aggregate should only rely on its state. Let's say the user want to buy a product I have to check if he has enough balance and in order to do that I need to know the price of product. So read model not allowed, aggregate query not allowed. what options do I have here?
...ANSWER
Answered 2022-Mar-08 at 16:01First of all, regarding your handle, you're not stupid :)
A few points:
In many situations you can query the read model even though there's eventual consistency. If you reject a command that would have been accepted had a pending update become visible in the read model, that can typically be retried. If you accept a command that would have been rejected, there's often a compensating action that can be applied after the fact (e.g. a delay between ordering a physical product and that product being delivered).
There are a couple of patterns that can be useful. One is the saga pattern where you would model the process of a purchase. Rather than "user A buys product X", you might have an aggregate corresponding to "user A's attempt to purchase product X", which validates and reserves that user A is able to buy X and that X is able to be purchased.
Every write model with an aggregate implies the existence of one sufficiently consistent read model for that aggregate. One can thus define queries or "read-only" commands against the write model. CQRS (IMO) shouldn't be interpreted as "don't query the write model" but "before trying to optimize the write model for reads (whether ease, performance, etc.), give strong consideration to handling that query with a read model": i.e. if you're querying the write model, you give up some of the right to complain about the queries being slow or difficult. Depending on how you're implementing aggregates this option may or may not be easy to do.
QUESTION
Before I added spring-data-start-jpa
and h2-database
dependencies, it was throwing these errors.
I allowed Axon's auto-configuration to do its thing.
Here's the stack trace I got:
...ANSWER
Answered 2021-Nov-22 at 22:40Question is not understandable, please share more code with us to get detail answers. It seems like your two classes is dependent. As mdh mentioned in the comments, @Lazy can solve your problem.
QUESTION
So, I'm working on a PoC for a low latency trading engine using axon and Spring Boot framework. Is it possible to achieve latency as low as 10 - 50ms for a single process flow? The process will include validations, orders, and risk management. I have done some initial tests on a simple app to update the order state and execute it and I'm clocking in 300ms+ in latency. Which got me curious as to how much can I optimize with Axon?
Edit:
The latency issue isn't related to Axon. Managed to get it down to ~5ms per process flow using an InMemoryEventStorageEngine
and DisruptorCommandBus
.
The flow of messages goes like this. NewOrderCommand(published from client) -> OrderCreated(published from aggregate) -> ExecuteOrder(published from saga) -> OrderExecutionRequested -> ConfirmOrderExecution(published from saga) -> OrderExecuted(published from aggregate)
Edit 2: Finally switched over to Axon Server but as expected the average latency went up to ~150ms. Axon Server was installed using Docker. How do I optimize the application using AxonServer to achieve sub-millisecond latencies moving forward? Any pointers are appreciated.
Edit 3:
@Steven, based on your suggestions I have managed to bring down the latency to an average of 10ms, this is a good start ! However, is it possible to bring it down even further? As what I am testing now is just a small process out of a series of processes to be done like validations, risk management and position tracking before finally executing the order out. All of which should be done within 5ms or less. Worse case to tolerate is 10ms(These are the updated time budget). Also, do note below in the configs that the new readings are based on an InMemorySagaStore
backed by a WeakReferenceCache
. Really appreciate the help !
OrderAggregate:
...ANSWER
Answered 2021-Sep-17 at 12:39Your setup's description is thorough, but I think there are still some options I can recommend. This touches a bunch of locations within the Framework, so if anything's unclear on the suggestions given their position or goals within Axon, feel free to add a comment so that I can update my response.
Now, let's provide a list of the things I have in mind:
- Set up snapshotting for aggregates if loading takes to long. Configurable with the
AggregateLoadTimeSnapshotTriggerDefinition
. - Introduces a cache for your aggregate. I'd start with trying out the
WeakReferenceCache
. If this doesn't suffice, it would be worth investigating the EhCache and JCache adapters. Or, construct your own. Here's the section on Aggregate caching, by the way. - Introduces a cache for your saga. I'd start with trying out the
WeakReferenceCache
. If this doesn't suffice, it would be worth investigating the EhCache and JCache adapters. Or, construct your own. Here's the section on Saga caching, by the way. - Do you really need a Saga in this setup? The process seems simple enough it could run within a regular Event Handling Component. If that's the case, not moving through the Saga flow will likely introduce a speed up too.
- Have you tried optimizing the
DisruptorCommandBus
? Try playing with theWaitStrategy
, publisher thread count, invoker thread count and theExecutor
used. - Try out the
PooledStreamingEventProcessor
(PSEP, for short) instead of theTrackingEventProcessor
(TEP, for short). The former provides more configuration options. The defaults already provide a higher throughput compared to the TEP, by the way. Increasing the "batch size" allows you to ingest bigger amounts of events in one go. You can also change theExecutor
the PSEP uses for Event retrieval work (done by the coordinator) and Event processing (the worker executor is in charge of this). - There are also some things you can configure on Axon Server that might increase throughput. Try out the
event.events-per-segment-prefetch
, theevent.read-buffer-size
orcommand-thread
. There might be other options that work, so it might be worth checking out the entire list of options here. - Although it's hard to deduce whether this will generate an immediate benefit, you could give the Axon Server runnable more memory / CPU. At least 2Gb heap and 4 cores. Playing with these numbers might just help too.
There's likely more to share, but these are the things I have on top of mind. Hope this helps you out somewhat David!
Second ResponseTo further deduce where we can achieve more performance, I think it would be essential to know what process your application is working on that take the longest. That will allow us to deduce what should be improved if we can improve it.
Have you tried making a thread dump to deduce what part's take up the most time? If you can share that as an update to your question, we can start thinking about the following steps.
QUESTION
Hello I am trying to start studying about es, microservices and then I would like to know about the command bus I basically believe that his responsibility is just to execute the command handler? does it necessarily have to be a queue? can you make kafka as a command bus or redis? I have a simple command bus implementation, but I would like to implement a command bus to be used the same command bus for 3 microservices, the way I did I would have to have a command bus for each ms, and register the commands and the commands handlers for each micro service
impl with typescript :
...ANSWER
Answered 2021-Apr-28 at 08:05You typically don't need a command-bus/queue, instead send the commands from the user/client directly to the Commandhandler/aggregate.
Kafka is better suited for event-driven architectures, where various services post events representing thins that happened and then for other services to consume.
Also, CQRS/EventSourcing are patterns you apply within one service (bounded context) and not across multiple services. You can use events to communicate between services, but this a separate thing, just like what this picture tries to show:
Events on the inside is not the same as events on the outside
QUESTION
Hello I have a command bus, a query bus, which basically has a keypair with the name of the command or query and the handler and then I execute the command that should publish my event. But I have some doubts about how I could do my event-bus. is the command-bus part of an event-bus? how could I do an event-bus with the handlers
command-bus:
...ANSWER
Answered 2021-Mar-24 at 13:47I see there's some confusion between the various Buses and the Event Store. Before attempting to implement an Event Bus, you need to answer one important question that lies at the foundation of any Event Sourcing implementation:
- How to preserve the Event Store as the Single Source of Truth?
That is, your Event Store contains the complete state of the domain. This also means that the consumers of the Event Bus (whatever it ends up being - a message queue, a streaming platform, Redis, etc.) should only get the events that are persisted. Therefore, the goals become:
- Only deliver events on the Bus that are persisted to the Store (so if you get an error writing to the Store, or maybe a Concurrency Exception, do not deliver via bus!)
- Deliver all events to all interested consumers, without losing any events
These two goals intuitively translate to "I want atomic commit between the Event Store and the Event Bus". This is simplest to achieve when they're the same thing!
So, instead of thinking about how to connect an "Event Bus" to command handlers and send events back and forth, think about how to retrieve already persisted events from the Event Store and subscribe to that. This also removes any dependency between command handlers and event subscribers - they live on different sides of the Event Store (writer vs. reader), and could be in different processes, on different machines.
QUESTION
I'm trying to integrate my nestjs application's cqrs setup with a external message service such as Redis. I've found a pull request and a comment on the nestJS github stating that I should be able to integrate my query/event/command bus with external services since version 7.0 of cqrs.
I've been trying to implement this, but I can't find much information from nestjs on the subject. The only thing I could find was an outdated configuration example and an open topic on github for creating tutorials on how to implement this. I managed to replace the default publisher and subscriper by going off the limited help I could find on github about this topic, but I don't really understand how I can use that to connect to the external service or if this is the best approach for this problem.
EventBus
...ANSWER
Answered 2020-Nov-17 at 15:28So after a couple days I managed to find two approaches to connecting to an external eventbus. I found out that I don't really need an external command or query bus as these come in through API calls. So if you want to connect to an external eventbus with NestJS here are the two options I found:
- Via a custom publisher & subscriber
- Via the NestJS Microservice package
The two approaches mainly differ in the way they connect to the external eventbus and how they handle incoming messages. Depending on your needs one might suit you better than the other, but I went with the first option.
Custom publisher & subscriber
In my application I was already using manual publish calls to my eventbus by using the EventBus class from NestJS and calling .publish()
for my events. I created a service that wrapped around the local NestJS eventbus together with the custom publisher and custom subscriber.
eventBusService.ts
QUESTION
Lately I have some issues with Autofac.
I have an aggregate service like this:
...ANSWER
Answered 2020-Oct-28 at 12:28The issue was Assembly scanning in .net core 3.1. The old - non working way:
QUESTION
I have been exploring Microservice Architecture, and even though the technologies I use are in Microsoft Domain, the question is generic.
I get the Idea of API Gateway esp for things like Authentication. The pattern I am roughly following is based on CQRS + Event Sourcing
Request-> Command ##CommandBus##->CommandHandler -> Change Aggregate State->Store Events-> PublishDomainEvents ->Publish Integration events ##Event Bus## -----> Update Read Models
Many times initial Command will be handled by ProcessManager (consumer) to Orchestrate workflow.
All Microservices Application Layer consume Command from Bus and work on changing Aggregate state. Once done, the Read model store is updated. Currently, there is only a single Read Database which is updated
When I started with Command Bus, The REST API per microservices were for mainly Get requests ( Read ), which would dip into the same Read Database as all other Services and rest for accepting Command from Gateway.
Based on my current Scenario, Is there a logic in having REST API's per Microservice? I know we can do Async with Rest API to push commands, but what is the point when I am already using a Bus.
But now I am thinking of not having API per Service but rather API's based on usage. It's then not limited to single Gateway but few Gateway API projects.
Are there any Cons/ pitfalls with this approach?
Edit 2-- **Trying to rephrase if it gives context ** My microservice structure is very similar (to what @mrdnk commented) . As you In I will introduce technology to make it more clear. I use Mass transit over RabbitMQ for inter service communication.
As of now I have API gateway used by client applications, which would then call appropriate microsservice API to push a command object. the API method itself acts as a Command Handler (acting as Application layer) calls Aggregate and make it undergo changes. Domain Events based on the change are published within the process with Mediatr. Any events that outside (microservice) world needs to know is published on the bus. I started to look at the communication and said to myself why not use the Bus also for commands (as command bus). That way I can have more reselient and async process.
Application layer will listen to command and handle appropriately. This way I feel the service is more encapsulated. On API side (individual microservce) I dont need to expose any rest api for use by gateway. API in Gateway wil listen to request and create command object. this will be queued to bus. Consumer (command handler) on Microservice will consume Command and so on.
Currently all Writes are eventsourced (mongodb). Reads go to SQL Server. I can create API just for Queries from Read side. No more need to have Http API from Microservice at all.
I know technically it would work but Dont know if there are any pitfalls.
Regards, Mar
...ANSWER
Answered 2020-Aug-19 at 07:13I think it is a good idea to have Microservices communicate with each other asynchronously and in practice I also use this appraoch with a mix of orchestration and choreography depending on the use cases.
Concerning the public API which you expose to your clients (e.g. web clients) over the internet it really depends on the determining factors and the options you are given. If your clients require REST based communication I would recommend to provide a fast response to the client synchronously by just providing the information that it went through Ok and some kind of unique id.
So if you think of an order request of an online shop the API gateway would forward the request to the order Microservice (either via REST or in your case via Messaging and some translation from asynchronous to synchronous response at the API gateway layer). Anyway, there should be some kind of immediate response to the client the order service can provide which could simply contain the id of the new order. Everything else for processing the order will than happen asynchronously either completely via an event-based choreography (started by an OrderRequestReceived event or whatever name fits the domain language) or via some kind of workflow orchestrated by the order service (but still with asynchronous messaging).
The client can then always use the order id to query the current state of the order which you will than provide based on the read model you are building.
If you are free to implement the client the way want you can also look into WebSockets, using HTTP/2 to allow for pushing of status changes rather than requiring the clients to poll for the current state. Or you could even look into gRPC...
QUESTION
I'm using Axon 4.3 with JPA/Spring. I want to inject entityManager in my interceptor, so i used ContainerManagedEntityManagerProvider in my configuration. but i have this error when i run my application
...Description: Parameter 0 of method configureCommandBus in AxonConfig required a bean of type 'org.axonframework.springboot.util.jpa.ContainerManagedEntityManagerProvider' that could not be found.
Action: Consider defining a bean of type 'org.axonframework.springboot.util.jpa.ContainerManagedEntityManagerProvider' in your configuration.
ANSWER
Answered 2020-Aug-10 at 11:03The ContainerManagedEntityManagerProvider
instance created by Axon, if you are using the Spring Boot Starter, through the JpaAutoConfiguration
looks as follows:
QUESTION
Having the following class hierarchy in a Deno Typescript project:
AccountPutController.ts
...ANSWER
Answered 2020-Jul-06 at 14:15this
is determined when you're calling a function. How are you invoking your handle
method?
Consider this example:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install commandbus
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page