Can one ensure one database connection per HTTP request with Express? #17076
-
I made this question in Stack Overflow: https://stackoverflow.com/questions/77975527/is-sequelize-flawed-how-to-ensure-independent-db-connections-in-an-express-serv In a NutshellIt appears to me that |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
It depends on what you're trying to do. If your goal is to have each request use their own connection, but all connections go to the same database, you can use await sequelize.withConnection({ destroyConnection: true }, async connection => {
// These two queries will run on the same connection
const entity = await YourModel.findOne({ connection });
await entity.destroy({ connection });
// The connection will be closed at the end of this function
}) The problem with this is that it's not a use case Sequelize is designed for because it's a lot less efficient than pooling and sharing connections. For instance, all DB queries made by this connection will be done in series, because a DB connection can only process one query at a time. If the issue is that you need multiple Sequelize instances because they connect to different databases, but each database has the same structure, then you need to create a copy of each model per Sequelize instance. Models can only be associated with one Sequelize instance (this is what Alternatively, you can wait for support for the Repository mode, but we've barely scratched the surface of the work that needs to be done to get there so it's years away. Repository mode allows your to use the same model class with multiple sequelize instances, as the model class is only a data holder and is not tied to a specific Sequelize instance. Finally, if you can explain why you need independent connections per HTTP request, we can probably help you further |
Beta Was this translation helpful? Give feedback.
They indeed use the same Sequelize instance but a single sequelize instance can have many connection to the database (by default it's 5 concurrent connections, but can be configured)
So what would happen if two concurrent HTTP requests each started their own transaction would be that both would execute the following step concurrently: