I’ve made a TCP server for a turn-based game in C#. The server uses MySql for the database and uses stored procedures for all database interactions. All database interactions are contained within a repository layer which is injected into a service layer. These services are then injected throughout the server. The database interactions currently include Inserts/Selects/Updates for the following
- Logging
- Account System
- Match history
- Player Stats
I need the server to scale to thousands of concurrent clients. I began load testing and quickly hit a wall with the MySql error ‘Too Many Connections’. At any given time, the server may need to call X amount of stored procedures, but there is a limit on how many connections I can have open at any given time.
What I’ve considered:
- The only solution I’ve thought of so far is to have some kind of event system queue where you can add a database request to a queue, the queue fires off these requests based on a max connection number and an event gets fired when each request is complete containing the return data. However, I’ve not done this before so I don’t have a clear idea on implementation.
What answer I’m hoping to get:
A solution on how I could scale the server to handle X amount of database calls when there is a limited number of available connections. Ideally with a written example in C# or pseudo code.
2
Answers
As AndrewR suggested, I had a look at connection pools and I ended up writing my own. Not sure if it's particiularly efficient but I've tested it with a load of 10,000 users (bots) and it seems to be working. Here it is:
NOTES
Interfaces:
DbConnection.cs
DbConnectionPool.cs
Create a singleton of DbConnectionPool. You can then get a connection by calling GetConnectionAsync(). Here is how calling GetConnectionAsync might look:
You are looking for a connection pool – a layer in your application which will open a fixed number of connections and allow higher layers to use those.
Higher layer will request a connection from the pool, execute operations and release the connection back to the pool.