r/cprogramming • u/wit4er • 15m ago
Simple connection pool in C
Hello, C community, while working on arena allocator for my in-memory database kevue (KEy-ValUE), I came to conclusion that memory management with arenas is not that trivial, in most cases you can't just allocate a big chunk of memory and forget about it. For example, a TCP server is a long running program, it should accept, manage and close connections, allocate and deallocate memory for connection metadata. With standard allocators like malloc, it seems trivial (lol) to manage memory: you malloc on accept and free on connection close, after that, you dont care what happens to freed pointer, everything is managed by magical malloc. With arenas the situation is different: it is you, the programmer, who asks for memory and it is your responsibility to return it back. So, I faced the reality of my previous design not being sutiable for arena allocators because the free operation in arenas simply doesn't exist - we allocate once and dealocate once, all intermediate frees are no-ops. Of course there are ways to fix this "problem" with arena but I prefer to keep it simple until I really need sophisticated solutions.
So, how can we manage connections without having to allocate and deallocate them constantly? Right, we need to create a pool of pre allocated connections to reuse them insted of destroying!
The API of the pool is simple: it will have only four methods:
ConnectionPool *connection_pool_create(Allocator *ma);
Connection *connection_pool_get(ConnectionPool *pool);
bool connection_pool_put(ConnectionPool *pool, Connection *c);
void connection_pool_destroy(ConnectionPool *pool);The signatures of these functions are self-explanatory: you create some connection storage, get connections from it, put them back, repeat, and when you no longer need this pool (e.g. server is stopped), you destroy it. Sounds very easy but how it works under the hood?
First of all, ConnectionPool structure:
typedef struct ConnectionPool ConnectionPool;
struct ConnectionPool {
ConnList conn_list;
FreeConnList free_list;
u64 chunk_size;
Allocator *ma;
};And other stuff:
struct Connection {
u64 id;
/* metadata */
};
typedef struct ConnList {
Connection **ptr;
u64 len;
u64 cap;
} ConnList;
typedef struct FreeConnList {
u64 *ptr;
u64 len;
u64 cap;
} FreeConnList;ConnList stores the list of all connections ever allocated for this pool, FreeConnList stores information about connections currently available for reuse. In my case, both these fields are dynamic arrays (hey, tsoding!). ConnList is an array of pointers to allocated Connection structs, FreeConnList store indexes of these array, but only for free connections. Each connection has an identificator that is also equal to index in connection list array. So far, so good. But what about chunk_size? I forgot to mention that out pool is dynamic meaning that it can grow and maybe even shrink depending on load! The chunk_size is how much the pool size changes, a granularity.
Let's create out connection pool by initializing and populating these structures:
ConnectionPool *connection_pool_create(Allocator *ma){
/* Allocate memory for pool itself */
ConnectionPool *pool = ma->malloc(sizeof(*pool), ...);
/* how many connections we need currently */
u64 chunk_size = 128;
pool->chunk_size = chunk_size;
/* Allocate memory for connection structs */
Connection *conns = ma->malloc(chunk_size * sizeof(*conns), ...);
for (u64 i = 0; i < chunk_size; i++) {
/* Populate structs with data here, set id equal to i */
}
/* Initialize connection list */
dyna_init(ma, &pool->conn_list, pool->chunk_size);
/* Copy connections pointers to dynamic array */
Connection **dst = pool->conn_list.ptr + pool->conn_list.len;
for (u64 i = 0; i < chunk_size; i++) dst[i] = &conns[i];
pool->conn_list.len += chunk_size;
/* The same way init free list and copy indexes, initially all are free */
/* return */
return pool;
}But wait, why we need to copy pointers to another array, if conns array already has all information? The reason is that we maybe need to grow our pool in the future and all existing connections should remain stable and valid. That means we cant simple reallocate conns especially within our arena. What we do instead is use conn list array is a storage for all future mallocs, it is reallocation but in a centralized place we control, lets see a get operation to understand it:
Connection *connection_pool_get(ConnectionPool *pool)
{
/* happy path, we found connection in a free list 0(1) complexity */
if (pool->free_list.len > 0) {
u64 cidx = dyna_pop(&pool->free_list);
return pool->conn_list.ptr[cidx];
}
/* if free list is empty, that means we need more connections right now! */
u64 chunk_size = pool->chunk_size;
/* increase connection list array by another chunk size */
dyna_expand(pool->ma, &pool->conn_list, chunk_size);
/ * malloc new connections */
Connection *conns = pool->ma->malloc(chunk_size * sizeof(*conns), ...);
/* save new index */
u64 last_idx = pool->conn_list.len;
/* Populate structs with data here, set id equal to i + last_idx */
/ * populate dynamic arrays like we did during create but now starting from last_idx */
/* return connection from newly allocated list */
return c;
}So, we allocated a new chunk of connecitons, added them to lists, and returned connection to caller. On next get we again on happy path.
Now let's look at put opetation (it surprasingly very simple):
bool connection_pool_put(ConnectionPool *pool, Connection *c)
{
if (c->id >= pool->conn_list.len) return false;
dyna_append(pool->ma, &pool->free_list, c->id);
return true;
}Just append connection id (index) to free list, thats it.
Now destroy:
void connection_pool_destroy(ConnectionPool *pool)
{
for (u64 i = 0; i < pool->conn_list.len; i += pool->chunk_size) {
pool->ma->free(pool->conn_list.ptr[i], ...);
}
dyna_deinit(pool->ma, &pool->free_list);
dyna_deinit(pool->ma, &pool->conn_list);
pool->ma->free(pool, pool->ma->ctx);
}It looks simple except for the first for loop: here we deallocate only starts of all allocated conns, and we know where these starts are just by adding chunk size, standard malloc will be happy.
So, now we have get and put with O(1) complexity and need no worry to individually manage connections. The only missing part is shrinkage of the pool, in the current design it only grows and doesn't take into accout load fluctuations. The simplest approach would be to assume that someday all connections will return to free list and we will have an opportunity to deallocate chunks, see below:
bool connection_pool_put(ConnectionPool *pool, Connection *c)
{
if (c->id >= pool->conn_list.len) return false;
dyna_append(pool->ma, &pool->free_list, c->id);
if (pool->conn_list.len > pool->chunk_size && pool->free_list.len == pool->conn_list.len) {
/ * deallocate all chunks but very first, shrink arena, etc */
}
return true;
}We check for conn_list length first because it doesn't make sense to destroy first chunk of pointers, but all other can be freed.
This is connection pool is not thread safe but adding locks around each operation should help. In my case I think i dont need thread safety because each thread in my server has separate connection pool and even separate allocator, only accesses to hashmap are thread safe.
Suggestions and corrections are welcome, as a beginner in C I obviously can't be very smart or efficient and the design presented here is not new, I basically was looking for simple solution and rediscovered it based on my current needs, who knows may be someone wil find it helpful Thanks!