I saw a map of undersea internet cables the other day and it’s crazy how many branches there are. It got me wondering - if I’m (based in the UK) playing an online game from someone in Japan for example, how is the route worked out? Does my ISP know that to get to place X, the data has to be routed via cable 1, cable 2 etc. but to get to place Z it needs to go via cable 3, 4?
That’s not how that works. The router merely sends the packet to the next directly connected router.
Let’s take a simplified example:
If you were in the middle of bumfuck nowhere, USA and wanted to send a packet to Kyouto, Japan, your router would send the packet to another router it’s connected to on the west coast*. From your router’s perspective, that’s it; it just sends it over and never “thinks” about that packet again.
The router on the west coast receives the packet, looks at the headers, sees that its supposed to go to Japan and sends it over a link to Hawaii.
The router in Hawaii again looks at the packet, sees that it’s supposed to go to Japan and sends it over its link to Toukyou.
The router in Toukyou then sends it over its link to Kyouto and it’ll be locally routed further to the exact host from there but you get the idea.
This is generally how IP routing works; always one hop to the next.
What I haven’t explained is how your router knows that it can reach Kyouto via the west coast or how the west coast knows that it can reach Kyouto via Hawaii.
This is where routing protocols come in. You can look up how exactly these work in detail but what’s important is their purpose: Build a “map” of the internet which you can look at to tell which way to send a packet at each intersection depending on its destination.
In operation, each router then simply looks at the one intersection it represents on the “map” and can then decide which way (link) to send each individual packet over.
The “map” (routing table) is continuously updated as conditions change.
Never at any point do routers establish a fixed route from one point to another or anything resembling a connection; the internet protocol is explicitly connectionless.
* in reality, there will be a few local routers between the gateway router sitting in your home and the big router that has a big link to the west coast