Description
Recently, we have received many questions regarding creating a large number of connections in go-redis. When a connection is deemed no longer available due to context or write/read timeouts, we remove it from the connection pool. We do this without any issues because the connection may contain dirty read/write data, which could potentially contaminate subsequent command invocations.
However, when ReadTimeout and WriteTimeout are set to relatively small values and the network status with the redis-server is poor, a large number of command timeouts occur, leading go-redis to create numerous new connections, further worsening the network environment.
-
Adding a connection recycling mechanism and marking network connections, such as "timeout - unread residual data" (which is the most common error). We would place these connections into a recycle bin, where periodic checks are performed to read and handle any residual dirty data. Once the connection is confirmed to be usable, it would be placed back into the connection pool. However, this approach would maintain a higher number of network connections than the value specified by pool.Poolsize, which might surprise users. Additionally, its effectiveness is limited when the network conditions are severely degraded.
-
Adding a network connection firewall that prevents the creation of new connections when a widespread connection rebuilding is detected, periodic health checks would be initiated. It is also possible to limit the creation of new connections by periodically injecting a certain number of healthy connections into the connection pool (similar to a token bucket algorithm).
-
We changing the mechanism of go-redis command read/write by implementing a read/write separation approach. Network connections would no longer have timeout significance, and the execution commands and expected results would be passed through mechanisms like go-chan. In other words, the connection becomes a stateless transport device.