I want to use PostgreSQL transaction isolation to ensure data correctness with optimistic concurrency control pattern where conflicting transactions are automatically retried, instead of my application doing upfront locking of database rows and tables.
One usual way to implement this is that the web application retries the transaction a specific number of times within a code block or replays the HTTP request by a middleware layer, also known as HTTP request replay. Here is an example of such a middleware for Pyramid and Python web applications web.
I did not find any good information on how Node.js and its PostgreSQL driver handle situations where there are two concurrent transactions in progress and one cannot go through because of reading and write conflicts. PostgreSQL will rollback one of the transactions, but how this is signalled to the application? In Python, PSQL driver would raise psycopg2.extensions.TransactionRollbackError
under this condition. For other SQL database drivers here are some exceptions they will raise.
This behaviour is more usual when you have set your SQL transaction isolation level to SERIALIZABLE, as you tend to get more conflicts under load, so I would like to handle it gracefully instead of giving HTTP 500 to users.
My question is:
How to detect dirty read rollbacks with PostgreSQL and some of the common ORM frameworks like TypeORM - if special handling is needed and the retry library cannot be independent?
Is there a middleware (NestJS/Express.js/others) to handle this and automatically try to replay the HTTP request N number of times whenever there is a transaction rollback from the database driver?