
Zero downtime deployments on a single port
For those of us working on microservices that sit behind routers, zero-downtime deployments are fairly straightforward: run multiple instances behind the router; stop accepting connections on the service we want to upgrade; wait for or terminate running connections; and then start a new instance. At least one instance of the service is always available, allowing us to release at any time, even when the service is busy.
But some services are bound to a single port on a single host - perhaps a sidecar on localhost, a service collecting metrics, a router, or even just clients hard-coded to point at a single destination. So, how can we do a zero-downtime deployment of something that is listening on a port that clients connect to directly?
This is in fact possible with the right socket options and shutdown process.
Example socket server
In this blog we’ll use a basic socket server written in Kotlin to illustrate how to achieve this, but the language used is not important, and it applies to anything running on a TCP connection, for example HTTP or database connections, whether encrypted or not, or whether blocking or async.
The following shows the socket server we will try to upgrade. It simply starts listening for connections on port 12000 and then echoes any text it gets back to the client:
fun main() {
// start listening for connections on port 12000
val server = ServerSocket(12000)
val executor = Executors.newVirtualThreadPerTaskExecutor()
executor.submit {
while (true) {
val clientSocket = server.accept()
// a client has connected; echo back the text they send in new thread
executor.submit {
echo(clientSocket)
}
}
}
}
(The echo function simply reads from the client socket and writes back, and is omitted here for brevity.)
Before we worry about zero-downtime deployments, we should think about graceful shutdowns: when we want to shut down the service, we want to stop accepting new sockets (by closing the server socket) and either waiting for client sockets to complete or terminate them after some timeout. In this example, we can register a shutdown hook to run when the process gets a shutdown signal like this:
Runtime.getRuntime().addShutdownHook(Thread {
// stop accepting new connections
server.close()
// wait for existing connections to finish
executor.shutdownNow()
executor.awaitTermination(10, TimeUnit.SECONDS)
})
Here we wait up to 10 seconds for connections to end and then abort them. But other approaches are valid: wait forever; wait for the socket to become idle for a certain time; or just close everything immediately. This really depends on your use case, for example in HTTP1.1, where a connection may be long lived but is mostly idle, a reasonable approach is to wait until each connection is idle for, say, five seconds.
Restarting with an outage
So, this is pretty easy and obvious: we will initiate a graceful shutdown with a SIGTERM signal; wait for the process to exit; and then start a new process.
The problem of course is that from the time we close the server socket, while we wait for in-flight connections to end and the process to end, and for the new process to start, we have an outage.
What if we could start two services listening on the same port? By default, you will get a socket error which most of us have surely experienced at one time or another:
BindException: Address already in use
SO_REUSEPORT to the rescue
There is a socket option we can apply which lets us bind multiple server sockets listening on the same port: SO_REUSEPORT. We need to set this before binding to the local port, and so in Kotlin our listening code looks like this:
val server = ServerSocket()
server.setOption(StandardSocketOptions.SO_REUSEPORT, true)
server.bind(InetSocketAddress("localhost", 12000))
As stated earlier, the actual language used here is not important, and this kind of option setting is similar in many languages.
Note though that the operating system does matter: this option is not always supported so you can detect it (either by querying the socket for its supported options) or catch and ignore exceptions. This is omitted for simplicity.
With this option, we can now start two servers listening on the same port at the same time!

Testing it out
Which instance will be used when a client connects to this port? The old one? The new one? Is it random?
Using telnet to make connections, we can try it out:
telnet localhost 12000
I connected and disconnected several times, and all connections went to the older instance:

In that test though, I only ever had up to one active connection. So, what happens if we open multiple connections from different clients at the same time?

Now it is connecting to both instances as if the operating system is load-balancing our port. It would be best to not rely on which process gets the connection, but in general they get more or less an even amount of connections.
Zero downtime deployments
Using the same graceful shutdown sequence (stop listening to new requests, wait for or terminate existing connections) having zero-downtime deployments is simple, as long as at least one process is always running.
We can also not worry so much about waiting for existing connections to complete; with a single process, if we waited 10 seconds for connections to end gracefully, that would translate to a 10-second outage. But now we could consider leaving an old process running for minutes, hours or even days while existing connections complete their work.
Note that in the case of a non-graceful shutdown, if we have two or more instances running, in-flight connections on the killed process would be killed but existing connections and new connections would not be affected.
Appendix: the full server code
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.StandardSocketOptions
import java.time.Instant
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
fun main() {
val server = ServerSocket()
// allow multiple processes to bind to the same port
server.setOption(StandardSocketOptions.SO_REUSEPORT, true)
// start listening for connections on port 12000
server.bind(InetSocketAddress("localhost", 12000))
println("Starting listening on port 12000 at ${Instant.now()}")
// start listening for client connections in a separate thread
val executor = Executors.newVirtualThreadPerTaskExecutor()
executor.submit {
while (true) {
val clientSocket = server.accept()
// echo back text to the client
executor.submit { echo(clientSocket) }
}
}
Runtime.getRuntime().addShutdownHook(Thread {
println("Shutting down")
// stop accepting new connections
server.close()
// wait for existing connections to finish
executor.shutdownNow()
executor.awaitTermination(10, TimeUnit.SECONDS)
println("Shutdown complete")
})
}
private fun echo(clientSocket: Socket) {
clientSocket.inputStream.bufferedReader().use { clientIn ->
clientSocket.outputStream.bufferedWriter().use { clientOut ->
println("Listening on $clientSocket")
var line = clientIn.readLine()
while (line != null) {
println("Read > $line")
clientOut.write(line)
clientOut.flush()
line = clientIn.readLine()
}
}
}
println("Socket ended gracefully")
}
Careers in Engineering
HSBC is delivering world-class digital banking now and for the future. Our engineering teams are at the forefront of delivering these innovative digital solutions.

Engineering careers for students and graduates
Shape the future of banking tech. Solve real problems and make an impact on a global scale.