architecturemicroservicessystem-design

Microservcies workers and api


I am building a microservice and I'm trying to figure out the best approach for workers

lets say I have a products service and this product service has in it there is an API and the products model, now some of the requests can come from a message broker like rabbitmq and those tasks usually perform a more demanding task like uploading images. should I move those tasks into a different microservice and share the model between them, keep them under the same service, or maybe there is a better option?


Solution

  • The real answer is: "It depends".

    My actual recommendation would be: Put the Controller and the Worker together in the same service. However do ensure that if you need to split the service in two (or in fact tree), you code is ready to do that. This is what we call Modular Monolith.

    A small example: Let's imagine your product controller is a basic CRUD. A call on POST, PUT, DELETE should produce a corresponding event productCreated, productUpdated, productDeleted. Persistence should be done in dedicated "place" (table, shema, index, ...) Same for the worker that will produce productImageUploaded Event. be sure to store those information in different 'place".

    Now, each time you need to modify the crud part based on some changes in the worker part (and the other way around). use the event to trigger it. To be clear. Your worker part should listen to the productDeleted event to clear the uploaded image (if this makes sens in your business)

    With that in place, you are ready to split the 2 modules because they don't depend on each other. Also, if you need to build an aggregated view of the Crud and the worker, you just have to listen to the event to do it. This way, you'll benefit of an easy developpement and deployement and as soon as you need to scale/split, you are ready to do this at small cost.

    This is ofc just an example. In your case, maybe all of this is already to much over engineering and you could build a basic service without any persistence split or event sent.

    I hope this help