Add TCP keepalive options for database connections - #4748
Conversation
✅ Deploy Preview for electric-next ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Thanks for the contribution, @tsg. Could you share the motivation and your use case that necessitates these options? |
|
@alco we have a SQL gateway in between electric clients and Postgres, and we had reports about the electric client not being connected for a while after GW restarts. I could reproduce the situation where the client loses the connection and doesn't attempt to reconnect for ~15 minutes if I kill -9 the gateway. On a graceful restart (i.e. if the RST or FIN makes it to the client) it works as expected. But besides the gateway there could be other network elements on the path that could cause RST/FIN to be lost. I think that by allowing tcp keepalive configuration one would have the knobs to ensure a quick reconnect regardless of what happens on the network layer. |
This adds the following config options. These are set on the underlying TCP socket.
ELECTRIC_DATABASE_TCP_KEEPALIVE_IDLE- Idle time before probing. EnablesSO_KEEPALIVEELECTRIC_DATABASE_TCP_KEEPALIVE_INTERVAL- Gap between probes.ELECTRIC_DATABASE_TCP_KEEPALIVE_COUNT- Unanswered probes before drop.ELECTRIC_DATABASE_TCP_USER_TIMEOUT- Max time data may stay unacknowledged.All unset by default, so behaviour is unchanged unless configured. Durations accept the usual 30s / 500ms forms.
Sample config:
Implementation:
ConnectionResolver.populate_tcp_opts/1now appends the options to:socket_options.SO_KEEPALIVEgoes through :inet's portable{:keepalive, true}; the rest use :raw with the LinuxIPPROTO_TCPoption numbers, guarded on:os.type()so non-Linux developer machines skip them rather than failing witheinval.Note: I've generated the PR with AI, because I don't know Elixir, but the change looks fairly straightforward to me, so I'm hoping it's all correct. The one thing that feels a bit risky is what happens on non-Linux kernels. The code attempts to disable this automatically in that case.
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.