Search code examples
socketstcpconnectionport

How TCP connections are distinguished during backend service communication?


Basically I know how browsers are attaching different port to each TCP connection by choosing free ephemeral port and therefore connection is unique, however I don't know how it looks like on TCP level when two backend services connect to each other. Is that similar to how browsers work?

For example let's say I'm sending request from some http client to 'Service A' that is running on 'thread-per-connection' server and listening on port 'X'. Within choosen endpoint I am also sending http request to 'Service B' that listens on port 'Y' (similar service or database), how will it start unique TCP connection between these two services, do 'Service A' acts simlilarly to how browsers handle that?


Solution

  • The outside HTTP client application is acting as a client to Service A. So that app will use an ephemeral port when making that 1st connection.

    Service A then acts as a client to Service B. So Service A will use an ephemeral port when making that 2nd connection.

    ----------       -------------           -------------
    | client | ----> | service A | --------> | service B |
    ----------       -------------           -------------
             ^       ^           ^           ^
             |       |           |           |
    x.x.x.x:e1   y.y.y.y:X   y.y.y.y:e2  z.z.z.z:Y