Distributed tracing for our MMORPG's servers with OpenTelemetry, Grafana Tempo and Alloy. Metrics say that something got slow, and logs say what one process did, while a trace follows one request through the login server, Redis, MySQL, a world and the saver, and shows where its time went. We write a small tracer of our own in C++ that speaks OpenTelemetry's protocol and W3C Trace Context's traceparent, and carry a player's way in across two servers through the token in Redis, a trade through a Redis stream to the saver, and a deploy to the world's next instance. Then trace ids in the logs, linked both ways in Grafana, and tail sampling in Alloy, which keeps the slow and failed traces. With MySQL two milliseconds away, the first traces showed each statement taking two round trips, so a connection now keeps the reads it's prepared, which halves a player's hello. This is episode 87 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.
Topics: Performance, DevOps
The code
Each step on screen is a tag in the game's repository. The code at the end of the episode is ep087/end.
- 3:46
ep087/step-1Where the traces goBrowseChanges - 9:28
ep087/step-2A tracer of our ownBrowseChanges - 33:15
ep087/step-3Two tracesBrowseChanges - 37:51
ep087/step-4One trace, through the tokenBrowseChanges - 47:09
ep087/step-5A trade and a deployBrowseChanges - 55:46
ep087/step-6Logs and samplingBrowseChanges - 1:01:02
ep087/step-7Two round tripsBrowseChanges - 1:06:44
ep087/endWriting it downBrowseChanges
Transcript
Intro
0:00 Hello again, and welcome to episode eighty-seven, where we're going to follow one request at a time through our servers with distributed tracing, from the login server, through Redis and MySQL, to a world and the saver. I'm quite excited about this one, as our very first traces found a slow spot I wouldn't have guessed. First, a quick look at one of them.
0:20 This is one player coming into the game's world, as a single trace in Grafana. The login server's work is on top, with its calls to Redis and MySQL, and under it, on another server, the world saying hello and loading the player. Each bar is how long its piece of the work took, so you can see where the time went.
0:39 As usual, all the code we write is on GitHub, and it's open source. The series' website links to it, and gives each episode a page, with its code at each of its steps.
Last time
0:51 Before we get to today's work, a quick look back at last time. Our film tool got the sky the server would send, and a camera that looks over a player's shoulder. Above the snow line, the rain turned to snow, and ash and fire fell on the Ashlands, with fireflies over the Meadows after dusk, wisps in the Crypt and sparks off the lava. The weather got its sound, first made from numbers, with thunder that comes after its flash, and then, for the rain and the fire, recordings. Today is a lot less pretty to look at, and quite a bit more useful, I think, so let's get going.
Why trace
1:25 Here's what we've had so far, with forty bots playing. The dashboard's metrics say how each world is doing, such as how long its ticks take. Say we had a chart of how long logging in takes, and its ninety-ninth percentile went up. It would tell us that it happened, and not where the time went, or in which process. The logs sit next to it, and each line is what one process did. To piece one player's login together, we'd match the login server's lines with the world's by hand, and they don't say how long the login took. The red lines are the bots asking for stories from a storyteller I haven't started here, so you can ignore those.
2:05 A trace follows one request through each process it goes through: the login server, Redis, MySQL, a world, and, for a trade, the saver. Each piece of the work is a span, with when it started, how long it took, and which span it's part of. So a slow login shows where its time went, and in which process. I think this is useful once a game has more than one server, as each server's logs and metrics see its own part of a request, and a trace puts the parts together. Some game studios trace their own servers this way. CCP, who make EVE Online, used Honeycomb to add tracing to a stack about twenty years old while they moved it to microservices, and InnoGames went with Jaeger.
2:48 We're not tracing the game's tick, as it isn't a request, and nobody waits on one tick alone. A span for each, twenty a second in each world, would be about one point seven million a day, for what Tracy and our tick duration metric already show. We trace work that's shaped like a request: logging in, entering a world, a trade and a deploy. And we're writing the tracer ourselves, speaking OpenTelemetry's formats, so the tools read it as they would anybody's. I prefer this to OpenTelemetry's C++ SDK, which would bring its own protobuf and curl into our build, while we have a JSON library and an HTTP client already, and a span is small enough to write and show you. So, today: somewhere to keep traces, with Tempo, Alloy and Grafana, then the tracer, a login and its world in one trace, trades and deploys, trace ids in the logs and sampling, and what the first traces found. All right, let's start with where the spans go.
Where the traces go
3:47 As usual, the version comes first: in the top CMake file, it goes up to zero point eighty-seven, for this episode's code. Next, Tempo, which is Grafana's store for traces, the way Loki is its store for logs. It runs here in a single process, which is plenty for one machine. It streams search results to Grafana as it finds them, over HTTP. Its API listens on port thirty-two hundred, and it logs warnings and worse. Its distributor is the part that takes spans in, in OpenTelemetry's protocol, which is OTLP for short, over gRPC, on port forty-three seventeen, OTLP's usual port for it. gRPC is Google's way of calling a service over HTTP two, with protobuf messages, and it's what Alloy is going to send in. The traces go on local disk, into a write-ahead log first, and then into blocks, which are what Tempo keeps and searches, under a volume we're about to add. Next is a part I'm quite keen on: Tempo's metrics generator makes metrics out of the spans as they arrive, such as how many requests each service gets a second, and how long they take, labelled as Tempo's. It keeps a write-ahead log of its own for them, beside the traces' one. It writes them into our Prometheus, each sample with an exemplar, which is the id of a trace it came from. We want two of its processors: the service graph, which is who calls whom, and span metrics, which count each kind of span and time it. So from the spans alone, we get how often each request comes, and how long it takes, to chart. And it doesn't send Grafana a usage report. In the compose file, Prometheus gets a command of its own, which starts with the config file and the storage path it had by default, as a command in Compose replaces the image's own. Its remote-write receiver lets Tempo write samples into it, as Prometheus usually scrapes its samples instead, and exemplar storage keeps the trace id that comes with a sample. Next comes the Tempo service, from Grafana's image, pinned like the others, so a new Tempo comes in when we decide to take it, and not before, with its config file and a volume of its own for the traces. Its API is on this machine's port thirty-two hundred, for us and our scripts, while Grafana reaches it inside Compose, and it starts after Prometheus, which it writes into. Alloy, which collects the containers' logs and profiles already, gets two changes. It gets a port: forty-three eighteen is OTLP over HTTP, so that a server we run on this machine, outside Compose, can send it spans too. It starts after Tempo, as it sends to it. Grafana's anonymous visitors become editors, as Explore, where a trace opens, is an editor's page. That's fine here, as Grafana listens on this machine and nowhere else, in production too. And the tempo volume goes at the bottom with the others. In the collector's config, three components make a pipeline for spans, each handing what it has to the next one's input. An OTLP receiver takes spans from our servers over HTTP, on forty-three eighteen, which they'll send to as JSON, and passes them on to the next component. That one is a batch processor, so Tempo gets fewer, bigger requests, and an OTLP exporter sends the batches to Tempo, over gRPC. It's plain gRPC without TLS, inside Compose's network, the way Loki and Pyroscope are reached. I like that our servers send to Alloy and not to Tempo, as what happens to the spans on the way, such as which ones we keep, is then Alloy's config, and not code in our servers.
7:19 Grafana gets Tempo as a data source, provisioned from a file, like Prometheus and Loki. Its uid is tempo, so other data sources and our dashboards can point at it, and it reaches Tempo's API inside Compose. The service map reads who calls whom from the metrics Tempo writes into Prometheus, the node graph draws a trace's spans as a graph too, and search results stream in as Tempo finds them. On Prometheus's side, a sample's exemplar, a field called trace id, opens in Tempo: a chart draws the exemplar as a dot, and a click on the dot opens that trace. There's a third dashboard, nanoMMO traces, which I'm pasting in, as it's a long file of JSON in Grafana's format. Its four panels are who calls whom, as a graph, then the requests a second and how long the slowest one in a hundred takes, both by kind. Last comes a table of the traces that took over a hundred milliseconds. We'll look at it once there's something in it. And in production's compose file, Tempo listens on the server's localhost, like Loki, while Alloy publishes no port at all, as the servers reach it on Compose's network.
A tracer of our own
8:27 Before the tracer, the handful of words tracing uses. A trace is one request's work, from one end to the other, and its id is sixteen random bytes, written as thirty-two hex digits. It's made of spans, each a piece of the work with a start and an end, and each span has an id of its own, of eight random bytes. A span also names its parent, the span it's part of, so a trace's spans make a tree, and that tree is the waterfall Grafana draws. Each span has a kind, too: a server span answers a request, a client span calls something else, such as Redis, and a producer puts a message somewhere, for a consumer to take later. In our tracer, the span that's open on a thread is that thread's current span, and a span started on the thread goes under it. To go from one process to another, a span's place is written down in W3C Trace Context's format, the traceparent: a version, the trace id, the span id and a flag, with dashes between them. Whoever reads it carries on in that trace, under that span.
9:28 The tracer gets a library of its own in the server's CMake file, called nanoMMO tracing, from a single source file, and the project's root as its include folder. Its header needs Prometheus's client, for a registry to count in, and Abseil's status types, while cpp-httplib, nlohmann's json and Abseil's random numbers are private to it, as they're how it works inside, along with Abseil's strings and time. The server's core library links it, so the login server, the worlds and the saver all get it, and the server's tests get a file for it. On to the tracer's header file, which brings in c std def and c std int, for sizes and the ids' fixed-width integers, and functional, for std function. Then memory, string and string view, Abseil's status and status-or, and Prometheus's registry, which we'll count dropped spans in. First, a span context, which is where a span is. The trace's id is sixteen bytes, so it's two sixty-four-bit integers, the high half and the low half, and the span's own id is eight bytes, one more. Keeping them as numbers makes them cheap to copy and compare, and we write them in hex as they go out. A span id of zero means no span at all, which is how the standard writes it too, so valid checks for that. Trace id writes the trace's id as thirty-two hex digits, as Tempo shows it, and the equals operator is defaulted, so the compiler compares the three fields for us, which the tests will use. The function traceparent writes a context out in W3C's format, and parse traceparent reads one back. It returns a status-or, so a traceparent that isn't written as the standard says comes back as an invalid argument error, and the caller decides what to do about it. The span kinds are an enum class, which is a scoped enum: its names don't spill into the namespace, and it doesn't turn into an int without a cast. They're numbered as OpenTelemetry numbers them, from one, so they can go out as they are. Internal is for work inside a process, server, for answering a request, client, for calling another service, producer, for a message put on a queue, and consumer, for one taken off it. Now the span, the class the rest of the tracer is about. A span is a piece of a trace's work, from when it starts to when it ends, or goes out of scope. While it's open, it's its thread's current span, which the next span started on the thread goes under. What a span records is a struct called data, which we declare here and define in the source file, so the header doesn't need vectors and variants, and no other file can reach into it. A span made without data records nothing, which is what we'll hand out while tracing is off, and the explicit constructor takes ownership of its data, through a unique pointer. The destructor ends the span, so a span that goes out of scope is recorded, the way a lock guard lets go of its lock. A span can be moved, out of a function that starts one, say, and can't be copied, as two copies would each record the span when they end. Recording says whether it has data, and context says where it is, for passing on. Attributes are keys with text, or with numbers, such as a player's id, and set error marks the span as failed, with why. End records it, and makes the span that was current before it current again, and going out of scope does that too. Privately, a span holds its data, and the context it replaced as its thread's current one, which is what end puts back. Sending spans is a std function that takes a batch, written as JSON, and says whether it went. That keeps the network out of the tracer's core, and our tests can hand it a function that keeps the batches in memory. Post to makes the one our servers use, which posts each batch to a collector such as Alloy. At most four thousand and ninety-six spans wait to be sent, and past that, a span that ends is dropped. Start tracing takes the service's name, the sender, and a Prometheus registry to count dropped spans in. It turns tracing on for the process, so from then on, its spans are that service's, and a thread of their own sends them, once a second or as soon as there's a batch. Tracing is off until it's called, so the tests, and a server run without a collector, record nothing. Stop tracing sends what's left, for two seconds at most, and turns it off. Start span starts a span under the thread's current span, or the first span of a new trace when there's none. Start child span starts one under the current span, and records nothing without one, as there'd be no request for it to belong to. That second one is for calls to Redis and MySQL: made for a traced request, they're traced, and made by the tick, they're not.
14:17 Now the tracer's source file, where after its own header comes cpp-httplib, the small HTTP library we've used for Consul's API, which is going to post the spans. Then the standard library's algorithm, atomic, for a pointer that several threads read, chrono, condition variable, c std def and c std int, iostream, memory, mutex, span, string and string view, thread, utility, variant and vector. Then Abseil's random numbers, its number parsing, str cat and str split, its clock and its time, nlohmann's json, and Prometheus's counter. First, what a span records, the data struct the header declared. It has a name, a kind, its context, its parent's span id, or zero for the first span of a trace, and its start and end, as nanoseconds since nineteen seventy, which is how OTLP takes times. Its attributes are a vector of pairs, each a key and a variant, which holds either text or a number, then whether it failed, and why. In an unnamed namespace, a batch is five hundred and twelve spans, and a batch goes once a second, or as soon as there are that many. As tracing stops, what's left goes within two seconds or gets dropped, so a collector that's slow, or gone, can't hold up a server that's stopping. A function called hex writes an id as sixteen hex digits, padded with zeros, with Abseil's hex formatter. Random id makes the ids, and they have to be ones nobody else has made, across all our servers, without asking anyone. It uses Abseil's bit gen, a random generator seeded from the system, and it's thread local, which means each thread gets one of its own, made the first time that thread asks. So no two threads share one, and there's no lock to take. It draws sixty-four random bits until they aren't all zeros, as zero is no id. With sixteen random bytes for a trace, two of our traces getting one id isn't something I'd worry about. Is lower hex checks text for lowercase hex digits with ranges all of, for reading a traceparent. Attribute writes one attribute as OTLP's JSON has it, as a key and a value, where the value says its type by the name of its field. Text goes in a string value, and a number goes in an int value, written as a string, which surprised me at first. A lot of JSON parsers read numbers as doubles, which can't hold all sixty-four-bit integers, so OTLP's JSON writes them as strings. A function named after the format writes a batch of spans as OTLP's JSON. For each span, we write its attributes first, as an array of keys and values, each through the attribute function. Its own fields go in a JSON object, which nlohmann's json lets us write as a list of pairs in braces. First come its trace id and its span id, in hex, which is how OTLP's JSON writes ids, while its protobuf form sends them as bytes. Next come its name, its kind as a number, which is why the enum's values are OpenTelemetry's, and its start and end, as strings of nanoseconds. The parent's span id goes in when there is one, and a span without it is the first of its trace, and a failed span gets a status with code two, which is an error, and its message. Around the spans, the resource is the service that made them, by its service name, and the scope is the code that traced them, which is ours, nanoMMO. The scope holds the spans, the batch holds the resource and its scopes, and the request holds the batches. It's a few layers of nesting, as OTLP was made to carry spans from many services and libraries in one request. Dump would throw at bytes that aren't UTF-8, so it replaces them instead, and one odd attribute can't lose us a whole batch. Minus one means no indenting, which keeps a batch small on the wire, and false leaves text that isn't ASCII as it is. Next is a class that takes spans as they end, from any thread, and sends them from a thread of its own, so ending a span doesn't wait on the network. We call it the exporter, as that's what OpenTelemetry calls this part. Its constructor keeps the service's name, the sender, and the counter for dropped spans, which can be null when nobody gave us a registry, and starts that thread, running the run function. Its destructor takes the lock, says it's stopping, gives the thread until two seconds from now, wakes it up and waits for it to finish. Its copies are deleted, as an exporter owns a running thread, and the style guide wants each class to say whether it can be copied. Take is how a span that's ended goes on the queue. When the queue is full, the span is dropped and counted. The thread ending it might be a world's tick, and I'd much prefer to lose a span than to make the tick wait. Otherwise it goes on the queue, and once there's a whole batch waiting, the sending thread is woken, after we've let go of the lock, so it doesn't wake up to a lock we still hold. Run is the sending thread's loop, which goes on until it's stopping and nothing's waiting. Each time round, it waits on the condition variable for a second, or until it's woken for a batch or for stopping. A condition variable lets a thread sleep until another one says something has changed, and it lets go of the lock while it sleeps. Once it's awake, it swaps the queue for an empty vector, under the lock, which is quick, and lets go, so other threads can queue spans while it sends. It sends what it took in batches of five hundred and twelve, and once it's past the time to give up, the rest are dropped and counted. Each batch is a std span over part of the vector, which is a view of the spans that copies none of them, written as JSON, sent, and reported. Report looks at how sending went, and spans that didn't go are dropped and counted, as more keep coming behind them, and holding on to them would fill the queue anyway. It keeps what it last said, to compare with what it would say now. So it writes to standard error when sending starts failing, and once more when it works again. A collector that's down for a minute would otherwise fill the log with sixty lines of one error. Drop adds to the counter of dropped spans, when there is one. The members are the service's name, the sender and the counter, what it last said, a mutex and a condition variable, and the queue of waiting spans. After them come whether it's stopping, and when to give up, which is the end of time until it's stopping. Of the members, the thread goes last, as members are made in the order they're declared, so the rest are ready before it runs. Outside the class, the exporter is behind an atomic pointer, set while tracing is on, and null while it's off. Atomic means any thread can read it while another changes it, safely, and reading it is cheap, which matters, as each span reads it. The current span is thread local too: each thread has its own, so a span started on the tick's thread doesn't go under a request on another thread. Start makes a span, and with tracing off, that's a span without data, and that check is all a span costs. It starts now, in nanoseconds since nineteen seventy. Under a parent, it's in the parent's trace, and the parent's span is its parent. Without one, it's the first span of a new trace, so it makes the trace's id. Either way, it gets a span id of its own. Out of the unnamed namespace, the trace id is both halves in hex, one after the other. A traceparent is version zero zero, the trace id, the span id, and the flags, zero one, which say the trace is being kept. Reading one takes more care, as it comes from another process. We split it at the dashes, and it has to have four parts. They're version zero zero, the one version there is so far, thirty-two digits of trace, sixteen of span and two of flags, all in lowercase hex, as the standard has it. Abseil's simple hex A to I reads the trace's first sixteen digits into a number, the high half we keep the trace's id in. Thirty-two hex digits are a hundred and twenty-eight bits, which is more than one integer holds, so the trace id is read in two halves. The last sixteen digits go into the low half, and the span's sixteen digits go into its own integer, in the context. If any of them fails, it's not a traceparent, and the error says what it was given, which helps when one arrives broken. Checking the digits before that matters, as a number parser would take a plus sign, which the tests are going to try. And a trace of all zeros, or a span of zeros, is no trace at all, so that's refused too, with an error that says so. Otherwise, the context comes back, and next are the span's own functions, where the default constructor makes a span without data. A span with data becomes its thread's current span as it's made, keeping the one it replaces, so spans started inside it go under it, without anybody passing it along. This is the bit I like most: the code that talks to Redis and MySQL doesn't need to know which request it's working for. Going out of scope ends it, as we said. Setting an attribute adds a key and its text to the span's list, when the span is recording, as a string it owns, copied from the view it's given. The second function adds a number instead, in the variant, and setting an error marks the span as failed, with the message. Each does nothing on a span that isn't recording, so the code calling them doesn't need to check, and with tracing off, that check is all they cost. End does nothing the second time, notes the end, puts the previous span back as current, and hands the data to the exporter, if tracing is still on. Post to returns a lambda that keeps a copy of the endpoint, as it's called long after post to has returned. It makes a new HTTP client for each batch, which once a second costs next to nothing. It gets a second to connect and two to answer, and posts the batch to slash v one slash traces, which is where OTLP over HTTP takes spans. A collector it couldn't reach is unavailable, and one that answered with anything but two hundred is an internal error, with what it said. Start tracing registers a counter, when it's given a registry. That's the registry the server's other metrics go in, so Prometheus scrapes it along with them. It's called nanoMMO spans dropped total, with help text that says it counts the spans that ended while the queue was full, or that the collector didn't take. And it swaps a new exporter in, deleting the one before, if there was one. Stop tracing swaps in null and deletes the exporter, whose destructor sends what's left. Start span starts under the current span, if there is one, and start child span gives back a span without data when there's no current span to go under.
24:48 Next, a good set of tests, as code like this fails quietly, with traces that don't show up in Grafana and no error anywhere, so I want each part pinned down. The tests bring in the tracer's header, cpp-httplib for a collector of our own, chrono, condition variable, c std def and c std int, memory, mutex, set, string, thread and vector. Then Abseil's status, status-or and str cat, GoogleTest, nlohmann's json to read what the tracer writes, and Prometheus's registry to read its counter. Using declarations bring the tracer's names in, so the tests read more easily. The example traceparent is W3C Trace Context's own, from the standard, so we test against what other programs agree on, and not against our own idea of the format. Our own servers would understand each other even with the format wrong, as they share this code, so it's the standard's example that would catch it. A fixture, tracing test, turns tracing on for each test that uses it. In set up, it starts tracing as a service called test, with a lambda as the sender, and the fixture's own registry for the counter. The lambda keeps each batch it's given, parsed, under a lock, as the tracer calls it from its own thread, and says it went. Parse with false at the end doesn't throw at bad JSON, and gives back a value we can check, which fits a code base without exceptions. Tear down stops tracing after each test, so one test's tracer doesn't leak into the next. And a function called spans stops tracing first, which sends whatever's left, and then flattens the batches into one list of spans, from the resource spans and the scope spans down. The fixture keeps the registry, the mutex and the batches as its members. The first test reads the standard's example, which has to parse, and when it doesn't, the assert prints the status, so we can see why. It checks the trace id, as thirty-two hex digits, and the span id, as a number, and writes the context back out as it was, so reading and writing agree. The second one is my favourite of the lot. Each case is the example with a single mistake in it, and the test before showed the example on its own reads fine, so we know each refusal is for that mistake, and not for something else in the string. Uppercase hex is refused, as the standard writes ids in lowercase. So is a version there isn't, version zero one. Next are a trace id a digit short, and one a digit long, and a trace id with a g in it, which isn't hex. Then, and this is the sneaky one, a span id with a plus sign in front, which a parser of numbers would happily take, and which is why we check the digits first. A part missing is refused, and one too many. None of these would come from our own servers, but a traceparent is text from another process, and I'd prefer to refuse one than guess what it meant. Spaces round the whole thing are refused too. So are a trace of zeros and a span of zeros, which the standard says mean no trace and no span, and an empty string, which is what a token's record without a traceparent is going to give us. Each one has to come back as an invalid argument, and when one doesn't, the failure prints the string, so we'd know which. Next, tracing is off until it starts, and this test runs without the fixture, so nothing has started it. A span records nothing, and has no context, and neither does a child. That's the state the rest of the game's tests run in, so they need no collector. With the fixture, a span goes out as OTLP's JSON, and this test checks the fields one by one. We give a login span a number, a text attribute and an error, keep its context, and let it end as it goes out of scope at the closing brace. One span arrives, with its name, its trace id, and its span id as sixteen hex digits, padded with zeros. It has no parent, as it started a trace, and its kind is two, for a server. The first attribute has our key, with the number seven written as a string, and the second has its text, and the status has code two, for an error, with our message. The times come as strings too, as a count of nanoseconds is far too big for a double to hold without rounding. The start is nineteen digits long, which nanoseconds since nineteen seventy will be for the next couple of centuries, so a time in seconds or milliseconds would fail here. And the end isn't before the start, which we can compare as text, as both have nineteen digits. Last, the batch's resource names the service it came from, which we write as a raw string literal, so the quotes inside it need no backslashes. Next, a span started inside another is its child, without anybody passing the parent along. With a login span open, a lookup span is in the login's trace, with a span id of its own. Once the lookup ends, a child span started next goes under the login again, as the current span goes back when a span ends. We end the token's span and the login's, and read what was sent. Spans arrive in the order they ended, so the login comes last, and both the others name it as their parent. A child span needs a parent, so on its own, with tracing on, it records nothing, and inside a hello, that call records. That's its valid twin, so we know the first one was refused for having no parent, and not because tracing was off. After that, a quick check that each trace and span gets an id of its own. A set keeps each value once, so two ids alike would leave it smaller. A thousand spans, each starting a trace of its own, go into two sets, one of trace ids and one of span ids. Both sets end up with a thousand ids, so none were made twice, and neither has an id of zeros. The next two take a bit more setting up, as they're about time and threads. To fill the queue, we need a collector that's busy, so this one's sender takes the first batch and holds on to it. It uses a mutex and a condition variable, a flag that says it's sending, another that lets it go, and a count of the spans it got. Once it's said it's sending, it waits until the test lets it go, and then counts the spans in the batch. So the first span goes to it, and once it's sending, ten more spans than the queue holds end behind it, while the collector sits on the first batch. Then we let the collector go, under the lock, wake it, and stop tracing, which sends the rest. The first span and a full queue went out, and the registry has one family of metrics, nanoMMO spans dropped total, with the ten that didn't fit. This one checks that stopping gives up on what's left after two seconds, which matters for a server that's stopping while the collector is slow or down. This collector takes half a second over each batch, and counts the spans in it under a lock, as it runs on the tracer's thread. Like the last test, it has a registry of its own, to read the counter from. We queue four thousand and ninety-six spans, which is eight batches, or four seconds' worth of a slow collector, and time how long stopping takes, with the steady clock. Stopping takes under three and a half seconds, the two seconds plus the batch it was in the middle of when it gave up. Some spans went, and some didn't, and what went plus what was dropped is all of them, so none of them go missing without being counted. Last, posting to a collector, over HTTP, where we make a collector of our own with cpp-httplib's server. It takes posts to slash v one slash traces, and answers a body that says refuse with five oh three, the way an overloaded collector would. Anything else, it checks is JSON and keeps, under a lock. It binds to a port the system picks, so tests running side by side don't fight over one, and listens on a thread of its own, which we wait for until it's ready. We trace to it with post to, end a span and stop tracing, so the batch has gone. A refused post comes back as an error, and then we stop the collector and join its thread. It got one batch, which we parse, and our login span is in it, by its name, and once it's stopped, posting to that port is unavailable, as nobody's listening there any more.
32:54 Let's build at this step and run the tracer's ten tests. They don't need MySQL or Redis, so dash dash no deps leaves those out, and grep keeps the lines of the tests that pass. The build takes a while, as the image builds the whole game again. Spans go out as OTLP's JSON, and all ten pass, the one that gives up after two seconds too.
Two traces
33:16 Now the servers start sending spans, and in the compose file, the login server and the world each get an environment variable, nanoMMO OTLP endpoint, with Alloy's address inside Compose. In the login server's main, we bring in string and the tracer's header. We read the setting, which Compose sets, and which is empty when we start a server by hand. When it's set, we start tracing as the service called login, posting to that collector, and say so in the log, so it's plain where the spans are going. Without it, the login server traces nothing, as before. Once the IO context has stopped, we stop tracing, which sends what's left, before the program says it's stopped. In the login server, with string view and the tracer's header brought in, a function called asked names a request by what it asks for, as its span's name. It's list worlds, then create account or log in when there's no session yet, as those come with a name and a password. With a session, it's enter world, then create character or delete character, and list characters when it's none of those. A span's name is how we'll search for it, so I'd like it to say what the player did, and not which function ran. In accept, once a request has been read, it's a server span of its own, from there to its answer, and as it's the first span on the thread, it starts a new trace. Entering a world notes which character, by its id. Further down, where the reply is ready, a reply with an error, such as a wrong password, is the player's mistake, so it goes on the span as an attribute called nanoMMO refused. A failure of ours, such as MySQL being down, marks the span as an error instead. Keeping those apart means the errors we search for are ours to fix. In password, hashing a password with Argon2id is a child span of its own, and so is checking one. They're slow on purpose, to make guessing passwords expensive, and I want to see how much of a login they take. The world's main brings in the tracer's header, and reads the setting as well, once the instance's name has been worked out from its registration. It starts tracing as its instance, such as Ember seven seven seven seven, as two instances of a world can run at once in a deploy. It passes its metrics' registry, so it counts the spans it drops. The login server serves no metrics, so its drops go uncounted for now, and the world stops tracing once it's stopped, like the login server. In the server, a player's hello, as they come into the world, is a trace of its own. When the token isn't redeemed, Redis not answering is our failure, so the span gets an error, while a token nobody issued, or a player who's already playing, is a refusal. Once we know who it is, the span gets the player's id, a lease held by another instance is a refusal too, and failing to lease or load the player is an error. And in players, loading a player and leasing one are spans under whatever's current, which is the hello.
36:12 Let's run it, building the game's images at this step and starting the login server, a world and the saver, with Tempo, Alloy and Grafana. Compose brings up MySQL, Redis and Consul first, as the servers depend on them. The build takes a few minutes, as each server's image builds the game. Next come twenty of the game's bots, from the load profile, logging in over twenty seconds, so there are logins and hellos to trace.
36:38 In Grafana's Explore, with Tempo as the data source, we search for the spans called enter world or hello. Each bot coming in makes two traces: the login server's enter world, and a moment later, the world's hello, each with a trace id of its own. Nothing says they're one player's way in, and the time between them, while the client connects to the world, isn't in either of them. The token is going to join the two.
One trace, through the token
37:03 To make them one trace, the trace has to get from the login server to the world, and something goes that way already: the token. When the login server lets a player into a world, issuing the token becomes a producer span, as the token is a message for the world. Its traceparent goes into the token's record in Redis, after the player's id. The world reads the token back as the client says hello, and the hello's span goes under the span that issued the token, in its trace. The world can't know which trace that is until Redis answers, so the hello's span is started then, from the time its message arrived. I prefer this to the client sending a traceparent in its hello: a client could send any trace it liked, while the token's record is ours, and goes from the login server to the world already.
37:52 Abseil's time moves to the tracer's public libraries in the server's CMake file, as its header is about to use it in a function's signature. In the tracer's header file, with Abseil's clock and time brought in, start span gets a second form, under a parent that comes from another process. It also takes a start time we give it, which is now unless we say otherwise. A request's work can start before we know which trace it's part of, and the hello is going to be that request. And a small function called in trace says whether the thread has a current span, so whether a call made right now is made for a traced request. In the tracer's source file, we go down to the unnamed namespace, to the function that makes each span, which is called start. Its signature gets longer, so it goes onto a second line. It gets a fourth argument, the moment the span begins, which used to be now. The two functions we had pass it now, as before. And the new start span passes on the parent and the time it's given, so a span can go under a context it was handed, and not the thread's current one. In trace is just whether the current span is valid, and start child span asks it first. In the tokens' header file, which now brings in the tracer's header, a token from the issue function carries the trace on, when it's issued for a traced request. Redeem takes an issuer, a pointer that's null by default, which it fills in with the span that issued the token, or no span, for a token that was issued outside a trace. Callers that don't care stay as they were. In tokens, with string view, utility and str split brought in, issuing a token is a producer span, under the request it's issued for, as the token is a message for the world. The world reads it a moment later, in a process of its own. The record that goes into Redis starts as the player's id, as before, and when the span is recording, a space and its traceparent go after it. A token issued with tracing off is the plain id, as it was. That record is what Redis keeps under the token's key, for the token's lifetime. Redeeming reads the record back with GET DEL, which reads and deletes it at once, so a token works a single time. With tracing off, the record is just the id, so reading it back has to cope with both kinds. We split it at its first space, into the id and the traceparent, if there is one. A pair of string views takes the two parts, without copying them. The id is read as it was, and a record whose id isn't a number is still an internal error. And when the caller passed an issuer, it's the traceparent read back, or no span, when there isn't one or it can't be read. A trace we can't follow is no reason to turn a player away, and a record from a login server that doesn't trace is the plain id, which still works. In the server's hello, we note when the message arrived, before anything else, then redeem the token with an issuer, which is a round trip to Redis. After that, we start the hello's span under it, from when the message arrived, so the wait for Redis is in it.
40:54 Next, the calls a request makes to other services. In Redis's client, with algorithm, span, str join and the tracer's header brought in, a function called start call makes a client span for a call. It takes the commands it sends as a std span, a view of one or more of them, so that one command and a pipeline of several go through it alike. The first thing it does is ask whether we're in a trace at all, and if we're not, it gives back an empty span, before it builds a name. The tick calls Redis each tick, and those calls cost that check and no more. It collects the commands' names, the first word of each, each name once, so a pipeline of many commands of one kind gets that name once, and it leaves out their keys and values. The names, joined with spaces, are the operation, and the span's name is Redis and the operation, such as Redis GET DEL, or two names for a pipeline of two kinds of command. Keys hold players' ids and tokens, which I don't want in a trace store. Each span says which system it is, db system, and what it asks, db operation, which are OpenTelemetry's names for them, and Tempo's service graph makes a node for Redis from the first. A command and a read pass their words as a span of one, with the vector's address and a count, and a pipeline and a transaction pass all of theirs. Each span starts before the call and ends as the function returns, so it times the whole round trip. And the tick's calls don't get this far. In the database, with string view, str split and the tracer's header, a function called start statement makes a statement's span, named by what it does, and to which table, from the SQL alone. Outside a trace, it stops at a check like start call's. It starts with an empty operation and an empty table, and a flag that says whether the table is the next word. We split the SQL into words at spaces, brackets, commas and new lines, skipping empty ones, and look at them in order. The first word is the operation, such as SELECT or INSERT. For an update, the table is the very next word. When a table is due, the word is the table, and we stop, unless that word is a SELECT, as in a count over a query of its own, where we go on to that query's table. Otherwise, a table is due after FROM or INTO, which covers our selects, deletes and inserts. The span is named MySQL, the operation and the table, so a player's load is MySQL SELECT players, with the system, the operation and the table as its attributes too. Its SQL goes in as well, cut at three hundred characters, as the saver's statements run to thousands of question marks. Our values have gone apart from the SQL, as question marks, since episode five, so a statement holds none of a player's data. Run starts a statement's span, and a transaction is a span with its statements under it, so the commit's time shows as its own. Consul's client gets a span of its own for each call, with string view and the tracer's header brought in. A function called start request makes it, from the method and the path it's given, after that check too. It cuts the query off the path, so the name doesn't change with what's asked, and the span metrics keep to a handful of names. Its name is consul, the method and the path, such as consul GET slash v one slash health slash service. Consul isn't a database, so peer service names it, which is what the service graph makes its node from, along with the method and the path, under OpenTelemetry's names for them. A put and a get each start one, so asking Consul for the worlds is traced, when a request does it.
44:31 Now a quick test that the token carries the trace on, with the tracer's header brought in. It turns tracing on with a sender that throws the batches away, as we're after the token's record, and not the spans. Inside an enter world span, as the login server would have, we note its context and issue a token for player seven. We stop tracing before redeeming it, as the world would be another process, without the login server's spans. Redeeming it gives player seven back, and an issuer in the enter world's trace, with a span of its own, which is the issue token span under it. And a token issued with tracing off is as it was. We redeem it with that issuer, which still holds the first token's span, and player eight comes back, with the issuer set to no span, so a stale one can't leak through.
45:18 We build at this step and run the tokens' tests. They need Redis, so Compose starts it first, with the rest the tests depend on, and the build takes a while again. The token carries the trace on, and the three older tests pass with it, so a token still works as it did.
45:36 Now each bot's way in is one trace, across both servers. On top is the login server's enter world, with its calls to Redis and MySQL under it. Next comes issuing the token, and under it, on the world, the hello, which starts a moment later, once the client has connected to the world. Under the hello, leasing the player in Redis, and loading them from MySQL, a statement at a time. I find it pretty satisfying to see the whole way in at once, with the gap between the servers right there in it.
A trade and a deploy
46:06 Next, two kinds of work that cross from one process to another in their own way. A trade that's done becomes a trace, from the ready that completed it. Saving its two players into Redis is a span, and putting the trade's record on the trades stream is a producer span, whose traceparent goes on the stream with the record. The saver takes trades off the stream each five seconds, and carries a batch on in a consumer span. A span has one parent, though, and a batch can hold trades from several traces, so it goes under the oldest, and links to the rest. A link points at a span in another trace, which Grafana lets you follow. And a handover, as a deploy moves a world's players to its next instance, becomes a trace too. It issues each player a token, the producer span from the last step, so each player's hello on the next instance joins the handover's trace, and a deploy is one trace across two instances. Going through a gate isn't traced, as a world's lands are copies in one process, and a player goes through as the world steps, without a request.
47:10 First, links, in the tracer's header file, where add link notes another trace's span that this span's work was for as well, as a batch's span is for each message in it, and has one parent. In the tracer's source file, the data a span records gets a vector of links, the contexts it was handed. As the span is written out, each link goes in its JSON as a trace id and a span id, in hex, like the span's own. Add link keeps one, when the span is recording and the other is a span at all, and does nothing otherwise. In the server, a trade completes when the second side says ready, so that's where we note the time, as the ready comes in. Once a ready has completed a trade, the trade is a trace of its own, started from that time, without a parent, as nobody's trace was going when the message came. Starting it from the ready means the time it took to complete the trade is in it. It gets the trade's id, which is also the id of the trade's record in MySQL, and both players. A trade that can't be saved, as one side's lease has moved to another instance, is an error, as both players are dropped, and neither keeps what the trade gave them. Further down, a handover is a trace of its own too, an internal span, as it's a deploy that asks for it, and not a player. It notes the next instance, by its host and port, and fails when the leases can't be passed over, and at the end, it notes how many players it told to move. Each of them got a token as they were told, which is the issue token span from before, under the handover's span, so their hellos join this trace. In players, with Abseil's clock and time brought in, a function called start saving trades makes the saver's span for a batch of trades. It takes the batch, and the moment the saver read it, so the span covers reading them from Redis too. Going through the trades, it reads each one's traceparent field, and keeps the contexts it can read, in the order the stream gave them, which is oldest first. A batch without traced trades gets a span that records nothing. One with them gets a consumer span, from when they were read, with a link to each trade after the first. Its attributes say it took messages from Redis, off the trades stream, and how many were in the batch, under OpenTelemetry's names for messaging, as with the databases' attributes. So the batch's span goes under the oldest trade's publishing span, as a span has one parent, and it's linked to the rest. Further down are the spans for the work, under whichever span is current. Passing the leases in a handover, which is one script in Redis, is a span, and so is saving players, once there's something to save, under the trade or the handover that asked for it. The trade's record goes on the stream with its bags, as before, and now it's a message for the saver, so publishing it is a producer span, when there's a trade. The command for the stream is built as before, but we keep a reference to it as it's added to the list of commands, which emplace back gives us. That reference is into the vector, so we use it straight away, before anything else is added. That way, the traceparent can go on its end as one more field, when the span is recording. A trade with tracing off goes on the stream as it did. In flush, which the saver calls each five seconds, we note the time before reading, and once they're read, the batch's span starts, from that time, and stays open while its statements run, so they go under it. A flush without trades, the players saved each five seconds, isn't traced, as nobody's waiting on it. The saver's main brings in the tracer's header, and once its metrics are being served, it reads the setting too, like the servers do. The trades it saves carry on their traces, so when the setting's there, it starts tracing as the service called saver. It passes its registry too, to count the spans it drops beside its other metric, and says in its log where the spans go. Once it's stopped and saved what was left, it stops tracing, so the last batch's spans go out. And Compose gives the saver Alloy's address, like the login server and the world.
51:14 Now a couple of tests, starting with links, in the tracer's tests, with the fixture. We start a publish trade span and keep its context, then a second, each starting a trace of its own, as two trades would. A batch's span starts under the first, as the saver's would, and links to the second. Three spans come out, in the order they ended. The batch's span is in the first's trace, and under its span, as its parent. Its links, as JSON, are a list with one entry, the second's trace id and span id, which we build as a string to compare with, taking the span id from the JSON. And that's another trace, so the link goes from one trace to the other. Next, in the players' tests, a trade's trace through the saver, against MySQL and Redis, with mutex, string view, nlohmann's json and the tracer brought in. This one's a bit longer than the others, as it goes through the world's half of a trade and then the saver's. We make the players, and a second character on the test's account, as a trade needs two sides, and the test stops if making the character fails. Each span goes into a list as it's sent, with a mutex beside it, and the sender parses each batch as it comes. It takes the lock, and adds the batch's spans to the list, one by one, as the tracer's thread calls it while the test goes on. Inside a trade span, as the world would have it, the two players are saved with a trade's record, whose id is the test's name, so tests running at once don't share one. Next comes the flush, outside any span, as the saver runs it, so if it's traced, it's because of the trade, and then we stop tracing, which sends what's left. A small lambda finds a span by its name, going through the spans in order, and gives back an empty object when there's none. We look up the publishing span and the saving span by name, as the calls to Redis and MySQL have spans of their own in between. Publishing the trade is a producer, kind four, and saving it is a consumer, kind five, under the publishing span, in the trade's trace. And the trade's insert into MySQL is in that trace too, so a trade can be followed from the ready to its row in the database. Last, it tidies away the second player in Redis and the trade's record in MySQL, as the test database is shared with the other tests.
53:31 We build at this step, and run the two new tests. The players' test needs MySQL and Redis, so Compose starts them first, with the migrations, and the build takes a little while. The saver carries a trade's trace on, and both tests pass.
53:47 Here's a trade as a trace, between two players run by the red-team client from episode seventy-two. On the world are the trade, saving both players, and publishing its record, which together take a few milliseconds at most. After a gap comes the saver's span, as the record waited in the stream for the saver's next flush. In the traces I looked at, that wait was between one point five and two point nine seconds, which none of our metrics would have shown me. Under the saver's span is its transaction in MySQL, with the trade's record and both bags.
54:19 And here's a deploy, where we started the world's next instance and stopped the first, with a hundred bots playing. The first instance saves everyone, passes their leases, and issues each player a token, in about six milliseconds. Then a hundred hellos arrive on the next instance together, and run one after another on its thread for about one hundred milliseconds, all of it in one trace of one thousand one hundred and three spans. Keep that block of hellos in mind, as we're going to come back to it.
54:49 With the trades and the deploy done, the traces dashboard has something to show. Who calls whom comes from Tempo's service graph, with a node for each service, from the bots, as user, to the login server, the worlds and the saver, with Redis, MySQL and Consul at the edges. The requests a second are by kind, from Tempo's span metrics, and so is how long the slowest one in a hundred takes. And the table lists the traces that took over a hundred milliseconds, the trades, with their wait in the stream, and the handovers. Each of them opens in Explore with a click. There's a surprise in there too, an account that took ten seconds to create. I ran the stack again afterwards and opened the slow ones, and nearly all of their time was MySQL inserting the account, not the password hashing I'd have bet on. My guess is the disk, with everything else on this machine writing to it as well, but it's a guess. What the trace did is turn "logins are slow sometimes" into one statement to look at.
Logs and sampling
55:47 Now the logs, and in the tracer's header file, trace field gives us the end of a log line: a space, trace id equals, and the current span's trace id, or nothing outside a span. In the tracer, it reads the thread's current span, so a line printed while answering a request knows its trace without being told. The login server's lines end with it, a failure, a login or a new account, and a refusal. And so do the world's, from a refused hello to a player joining, and a player who's dropped as a trade of theirs couldn't be saved. In Grafana, Loki's data source gets some settings of its own, starting with a derived field called trace id. A regular expression finds the trace id in a line, and turns it into a link to that trace in Tempo, labelled open the trace. And Tempo's data source goes the other way, from a span to our servers' lines with its trace's id, a minute either side of it.
56:44 With a hundred bots logging in, each with a handful of spans to a dozen and more, keeping all of them adds up, and most of them are the quick, boring case. The usual way to keep fewer is to sample at the head, deciding as a trace starts. The trouble is that at the start nothing's happened yet, so a slow trace, or one that failed, is kept as rarely as the rest, and those are the ones I want to read. So Alloy is going to sample at the tail: it holds each trace's spans until the trace is whole, and decides from all of them, which costs memory while it waits. It waits ten seconds from a trace's first span, as a trade's saver half comes up to five seconds after its world half. It keeps the traces with an error, the ones that took over a hundred milliseconds, and a tenth of the rest, to see what a normal one looks like. A span that comes after its trace was decided, such as a hello from a token issued thirty seconds before, follows that decision.
57:41 In Alloy's config, the receiver's output changes: it hands its spans to a tail sampler now, and the sampler hands what it keeps to the batch processor we already had. The tail sampler is a component that comes with Alloy, from OpenTelemetry's collector, so this is config, and no code of ours. It waits ten seconds from a trace's first span before it decides, which is long enough for a trade's saver half, and costs memory for each trace it's holding. It remembers its decisions for a hundred thousand traces each way, kept and not kept, so a span that comes after the decision follows its trace, and isn't decided on its own. The policies come next, and a trace is kept if any of them keeps it. The first, called errors, is a status code policy, which keeps the traces with an error status, as those are the ones we'll want to read. The second, called slow, is a latency policy, which keeps the traces that took over a hundred milliseconds from their first span to their last, as a slow request is what the metrics can't explain. And the third, a tenth of the rest, is a probabilistic policy, which keeps ten percent of the traces, picked by their trace ids. Keep in mind that Tempo makes its metrics from what's kept, so from now on, they count a tenth of the quick traces, and the dashboard's requests a second come out a lot lower than what the servers really get.
58:59 In Explore, this time with Loki, here are the lines our servers print as they answer requests, each ending with its trace's id. Say we're after one player's join, so searching for its trace id leaves the line it printed, and opening the line shows its fields, where the trace id is a link now. Open the trace, and it comes up beside the line, with the login server's half and the world's. A line's trace opens when Alloy kept it, though, and a quick one is kept a tenth of the time.
Two round trips
59:30 Until now, MySQL has been a container on this machine, with everything else, a fraction of a millisecond away. In production, the database often has a machine of its own, which can be up to a millisecond or two away across the network. So let's put MySQL two milliseconds away, with netem, which we first used in episode nine. We build the image of the Dockerfile's netem stage, and run tc in the network of the MySQL container, which delays what MySQL sends by two milliseconds. Dash dash cap add NET ADMIN lets tc change the container's network.
1:00:05 With a hundred bots coming in, here's one player's way in again. Each statement to MySQL now takes about four point seven milliseconds, a bit over twice the delay we added, so each one is two round trips. The hello takes about nineteen milliseconds, on the world's thread, the one that ticks. That surprised me, as I'd assumed a statement was a single trip to MySQL and back.
1:00:29 Since episode five, Database Run has prepared each statement, which is a trip to MySQL and back, then executed it with the values, which is another, and closed it, which MySQL doesn't answer. So that's two round trips for each statement. Our servers run a few reads over and over, such as loading a player, so a connection can keep the reads it's prepared, by their SQL, and run one again with the next values, in a single round trip. Writes are prepared each time, as before, so a connection that's gone stale is still found as a write is prepared, before it runs anything.
1:01:03 In the database's header file, with c std def and map brought in, the deleter that closes a prepared statement moves here from the source file, a small struct whose call operator closes it. Then the statement, a unique pointer with that deleter, moves too, as the class is going to keep statements now. A connection keeps sixty-four reads at most, which is plenty for the few the servers run, and the limit is there as each one takes memory in MySQL too. So a select is prepared the first time it runs, and kept, which makes it one round trip after that, not two. Executing a prepared statement becomes a function of its own, called execute, and the reads are a map from their SQL to their statement. The std less with empty angle brackets lets the map compare a string view with its keys, so we can look one up without making a string first. In the database's source file, connecting again clears the reads, as they were prepared on the old connection, and so does the destructor, before the connection closes. In run, once the statement's span has started, we look for its SQL among the kept reads. When it's there, we execute it, and that's one round trip. When that fails, it's forgotten, so it's prepared again next time. A connection that's gone stale since the read was prepared fails as it runs, as unavailable. A read changed nothing, so we can run it again on a new connection, unless we're in a transaction, which went with the old one, and any other error goes back to the caller. Otherwise the statement is prepared as before, and executed, and a select that worked is kept, while there's room. Moving the statement into the map means it isn't closed as the function returns. Execute is what run did after preparing, now on the statement it's handed. It checks the count of values, binds them, executes, and fetches the rows. Each statement dot get in it becomes the statement, as it's a plain pointer now. The rest is as it was: each value goes in as text, which MySQL converts to its column's type, and each row comes back as strings.
1:03:04 Let's pin it down with two tests against MySQL, with Abseil's number parsing and str cat brought in. The first one needs a test database, and is skipped when there's none, as the other database tests are. It counts the statements the connection has prepared, with a lambda, which asks MySQL for the session's status, and the count of prepared statements so far on this connection. The show is a statement too, so it's prepared as well, and counts its own prepare. The lambda reads the count out of the row's second column, as a number, and checks that it could, or gives minus one when there's no row at all, so a missing count fails the checks below it. The test's name gives us an account name nobody else uses. We take the count before we start, as other tests may have used the connection. Then a read runs three times, looking up an account by the test's name, which doesn't need to exist for this. The count has gone up by two: the read, once, and the show that counted. A write runs three times after that, a delete by that name, and the count goes up by four, three deletes and the show, as a write is prepared each time, as it was. The second test needs two connections to MySQL, and is skipped without them. Each comes from the tests' helper, test database, which connects with the settings the tests run with, so a connection here is one of our database objects. The plan is to pull the first one's connection out from under it, and check that its next read still works. The first connection reads its connection id, the number MySQL gave it, which keeps that read prepared on it. Then the other connection kills it, with kill and that id, as MySQL does to a connection that's sat idle for eight hours, or as restarting MySQL does to all of them. Running the kept read again works, and gives a different connection id, so it went to a new connection, as the old one, and its prepared read with it, had gone.
1:04:58 We build at this step and run the database's tests, which need MySQL, so Compose starts it first, with the migrations. A read is prepared once, and all three pass, the transactions' test from before as well.
1:05:11 And here's a player's way in once more, with MySQL still two milliseconds away. Each statement takes about two point four milliseconds now, one round trip and a little, and the hello about nine point nine.
1:05:24 Side by side, with MySQL two milliseconds away, a statement went from about four point seven milliseconds to two point four. Entering a world, on the login server, went from about fourteen point three to seven point two. The hello went from about nineteen to nine point nine, which roughly halves it, as each of its four statements lost a round trip. Without the delay, a hello takes well under a millisecond, so on one machine it hardly shows, which is how it's sat there since episode five without me spotting it.
1:05:55 The traces showed two more things, which I've not fixed yet. A handover's hellos, a hundred of them here, arrive together, and run one after another on the next instance's thread, the one that ticks. With the delay, that was one point nine five seconds without a tick, and with the reads kept, it's still about nine hundred and seventy milliseconds. And our tick duration metric can't see it, as the hellos run between ticks. The other is the login server, which checks passwords with Argon2id on its one thread, about forty-five milliseconds each. So a burst of logins waits in line, one behind the other, and a single trace can't show that wait, as its span starts once its request is picked up. I think both deserve an episode of their own, and the handover's hellos are in the decision record, so they don't get forgotten.
Writing it down
1:06:44 Last, the game's docs, starting with the monitoring page, which gets a section on tracing. It has a table of what's traced, and the spans in each, and what isn't, and why: the tick, going through a gate, the client, and the browser's way in. Then how a trace gets from one process to another, in the token and the trades stream, and what Alloy keeps. Next is how to read traces in Grafana and through Tempo's API, with a few searches to start from, and what the first traces showed, with the netem commands to see it for yourself. And the choices we made get decision record thirty-eight. We trace requests with a tracer of our own, which speaks OpenTelemetry. Its context is that the metrics, logs and profiles we had each say how one process is doing, and none follows a request from one process to the next. The decision is what we built today, piece by piece. The alternatives are the part I'd read first. The SDK would compile its own protobuf beside ours, along with curl, and its exporter writes JSON by way of protobuf anyway. Our tracer is about five hundred and fifty lines, comments and all, and swapping it for the SDK later would change how spans are made, and not where they go. Jaeger or Zipkin could keep the traces, but Tempo keeps them cheaply, by their ids, the way Loki keeps logs, sits in the Grafana we have, and makes the service graph for us. The client sending a traceparent is down here too, and so is sampling at the head. And the consequences say what it costs, such as a span for each call made for a request, and what's still open, like the handover's hellos. It goes in the index, as the thirty-eighth row.
Wrap-up
1:08:23 Today, our servers' spans started going to Alloy, which sends them on to Tempo, and Grafana reads them, with a dashboard of who calls whom. We wrote a tracer of our own, a few hundred lines that speak OpenTelemetry's protocol and W3C's traceparent. A player's way in is one trace across two servers, carried in the token's record in Redis, a trade goes through the trades stream to the saver, and a deploy is one trace across two instances. Log lines end with their trace's id, linked both ways in Grafana, and Alloy keeps the slow and failed traces, and a tenth of the rest. The first traces showed each statement taking two round trips, so a connection now keeps the reads it's prepared, and decision record thirty-eight keeps why we trace with a tracer of our own.
Playing it
1:09:59 If you've traced a game's servers yourself, or found something odd in a trace, I'd love to hear about it in the comments, along with what you'd like to see next. And if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.