Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chapter 13. Danger of using single UOW instance. #312

Open
donguklim opened this issue Sep 16, 2020 · 2 comments
Open

chapter 13. Danger of using single UOW instance. #312

donguklim opened this issue Sep 16, 2020 · 2 comments

Comments

@donguklim
Copy link

donguklim commented Sep 16, 2020

In chapter 13, Unit of work instance is no longer initialized in each api request as it did in chapter 12.
https://github.com/cosmicpython/code/blob/chapter_12_cqrs/src/allocation/entrypoints/flask_app.py

The message bus keeps using a single UOW instance.
This is not a problem if all messages are handled by a single thread.

However, on a multi-threading environment where each api request may be handled by different concurrent thread, there is possibility of losing events before events are collected to the queue in the message bus.

Before a thread execute bellow statement after it handles a message, https://github.com/cosmicpython/code/blob/chapter_13_dependency_injection/src/allocation/service_layer/messagebus.py#L44
if another thread executes with uow: statement, the repository instance in the singleton UOW is replaced to a new instance and all aggregate objects stored in the old instance are lost.
https://github.com/cosmicpython/code/blob/chapter_13_dependency_injection/src/allocation/service_layer/unit_of_work.py#L52

Found this problem while developing a GRPC server which is multi-threaded by default.
I fixed this issue by making message bus to keep a UOW instance generator function instead of the UOW instance.

@hjwp
Copy link
Contributor

hjwp commented Sep 16, 2020

You're quite right! I have a long-standing action to write a blog post about this and add a footnote to the book.

there's some existing discussion here if you're interested. cosmicpython/code#23 thanks for opening the issue here too tho. hope other people will find it too!

@dbaber
Copy link

dbaber commented May 4, 2024

@donguklim What does your "UOW instance generator function" look like?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants