Architecture decision records for our MMORPG, in C++. After seventy episodes, the code says what the game does, and a commit what changed, but neither says why the game is built this way, or what we weighed and turned down. So the game gets a folder of decision records, after Michael Nygard's format, one for each choice that would be costly to undo: the context, the decision, the alternatives considered and the consequences, with the episode each came from. We go through all twenty-four, from C++, an authoritative server and protobuf in episode one to MySQL, Redis, TLS, Consul, guilds and last time's delta compression, and see how a record is superseded instead of rewritten, as raylib's did Vulkan's. Plus a fix clang-tidy found, a const that kept a return from moving a string. This is episode 71 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.
Topics: DevOps
The code
Each step on screen is a tag in the game's repository. The code at the end of the episode is ep071/end.
Transcript
Intro
0:00 Hi, and welcome to episode seventy-one, where we're going to write down why the game is built the way it is, one decision at a time. So far, the reasons behind each choice are spread over seventy episodes, and the code doesn't keep them. First, a quick look at what we'll have by the end.
0:17 By the end, the game's docs have a folder of twenty-four decision records, with an index of them. They start from C++ and an authoritative server, in episode one, take in a choice we reversed in episode two, and come all the way up to the guilds, and last time's delta worlds.
0:33 The series' website links to the game's open source code on GitHub, and has a page for each episode, where you can browse the code at each of its steps.
Last time
0:43 A quick reminder of where we left off, first. Last time, we made the server send less. Each input says the newest world the client has whole, and the server remembers a second of what it sent each client, as a hash of each player's and monster's piece. Whoever hasn't changed since that world goes by their id alone, and the bots send their keys each tick, so they say often enough which world they have. With forty bots on one machine, each got roughly half the bytes it did before.
Today
1:15 After seventy episodes, the code says what the game does, and each commit says what changed in its step. Neither says why the game is built this way and not another, or what we weighed and turned down on the way. Say someone joins and asks why the worlds go over UDP. The answer is in episode nine, or in my head, and that's the part that gets lost first. So we're going to write a record for each choice that would be costly to undo, which is called an architecture decision record. Each says what forced the choice, what we picked, what else we weighed, and what it costs us. A record isn't rewritten once it's accepted, and a change of mind is a new record that supersedes the old one. I think teams should keep these, small teams too, as they're cheap to write while the reasons are fresh, and quite hard to piece back together a year later. We'll look at each record rendered, as Markdown, and I'll sum up the choice, what lost to it, and what we live with. Right, let's start with the version, and a fix.
A fix clang-tidy found
2:13 First, the top CMake file moves the project on to version zero point seventy-one. Then a fix in settings, on a line from episode sixty-five, which clang-tidy found. FileSetting builds the path to a file from the repository's folder, into a local string, and returns it. Returning a local by name moves it out of the function, which for a string hands over its buffer, without copying the text. But this string is const, and moving changes the object it moves from, so a const one can't be moved, and the return copies it instead. FileSetting runs a few times as a program starts, so nobody would notice the copy. However, clang-tidy has a check for it, called performance no automatic move, for the copies that do cost something, such as in a tick. And our clang-tidy settings make each of its warnings an error, which fails CI. So the const comes off the string, and the return moves it. Over the line, we write why it isn't const, so that nobody adds it back as a tidy-up. And as episode sixty-five is out, its steps stay as they are, so the fix is a step of today's.
What a record is
3:21 The records get a folder of their own in the docs, with a README on what a record is, and why we keep them. They're a short take on the architecture decision records Michael Nygard described in a post in 2011. The README gives four reasons to keep them, and the third is the one I'd use most. The reasons outlive the people who knew them. So whoever comes after us still finds why saving goes through Redis, which we decided in episode thirteen. Someone new can read them in order and get the architecture as it was built, which is how I'd like to start on a code base I didn't write. A settled question stays settled, so if someone asks why not a JSON web token, record eleven has the answer, and asking again means saying what's changed since. And reversing a choice takes a new record that says what's different now, so the game doesn't drift off a decision by accident. A record is for a choice that's expensive to back out of, like MySQL or protobuf, or one people keep asking about. A change that one commit could undo, or that the code makes plain, needs none, and I'd hold that line, as a folder full of small records gets skipped. Each record is a file, with the next number and a short title, and its sections are the status, the context with the episode it came up in, the decision, the alternatives considered, and the consequences. An alternative goes in if it was weighed, or if it's the obvious one, and then the record says nobody weighed it. And a record is accepted as it's merged, and isn't rewritten after, like a published step or a migration that has run. To change a decision, we write a new record, and set the old one's status to superseded by the new one, which is the single edit an accepted record gets.
The foundations
5:03 The records go in the order the choices were made, so the first one is the language, C++20, for the servers and the client. It says up front that no episode weighed another language, so it lists what came with the choice, and not why it won. I like that, as a record that makes up its reasons after the fact is worse than none. So Rust, or a garbage-collected language such as Go, sit in its alternatives for the servers, flagged as not weighed. And memory and threading bugs are ours to find, which is what episode twenty-eight's sanitizers, fuzzers and clang-tidy are for. Record two is the one I'd defend hardest: an authoritative server, at a fixed tick. The world server decides what happens in the world, and a client sends its keys and what it picked, but not where it is. In episode two, the client decided where its player stood, and with that, a modified client could put its player anywhere, without the others being able to tell. Over the internet, that puts a beat between your key and your player moving. Episode sixty-eight hides that for your own player, and sixty-nine smooths out everyone else. Next comes protobuf, as the contract between the client and the servers, from a proto file that all sides compile. JSON loses on size and on parsing: a message with one number in it, set to a hundred and fifty, is nine bytes of text, where protobuf's is three. And since a field's number is what goes on the wire, a field we remove is reserved, and no new field takes its number. With four, we build, test and check in Docker, on each push. A single Dockerfile, from Ubuntu's long-term support release, builds and tests the code, and each check is a stage, which CI runs as a developer would. Putting the compilers straight onto CI's machines is the obvious alternative, which nobody weighed, and with it CI and a laptop would build two different ways. One cost shows up on a bill: a private repository pays for CI's minutes, so its pushes get the tests, and the slow checks run at night. Five is particular to a series like ours: the repository's history is the curriculum, as each step is a tag a viewer can check out and build. Once an episode is out, its tags stay where they are, so a fix to published code is a step in a later episode, like today's in settings. Before that, a bug is fixed in the step that made it, where most projects would fix it where it was found. A viewer checking out an earlier step would then meet the bug with nothing to explain it. Each fix means replaying the commits after it and moving their tags, and I think that's worth it, as any step can be checked out and built.
Superseded, not rewritten
7:39 Records six and seven show how a decision changes. Six drew the client with Vulkan, and its status says superseded by seven, which links straight to it. It comes from the first version of episode two, from the tenth of October, and why Vulkan was picked then isn't recorded. Its consequences say why it went, as Vulkan is explicit. The client moved each image of the swap chain between layouts, waited on fences, and rebuilt the swap chain when the window was resized. A cube on a board of tiles, under a menu, came to about fifteen hundred lines of sources and shaders, without its tests. So seven, from the next day, draws with raylib, and the interface with Dear ImGui. Its reason is the series: we're here for the engineering around the game, so I want the graphics code small, and the time spent on the servers, the tests and deploying. It lists what was weighed then, OpenGL directly, which is easy to start with, Vulkan, which was the first version, and an engine, which would hide the engineering we want to look at inside it. At the end of episode two, the raylib client does more, with a lit cube, in about five hundred and fifty lines. In exchange, we're on OpenGL, an API Apple stopped updating years ago, for Metal, though it still works on today's Macs. I'd make that call again, and I like that the old record stays. Someone who wonders why there's a Vulkan branch lands on six, and six sends them on to seven. And in the decisions README's index, six keeps its row, with its status pointing at seven, so the reversal shows in the list too.
Servers and saving
9:14 Then the servers, starting with eight, which puts the world on one thread, on Asio's event loop. Accepting players, reading their sessions, the tick and the signals are each a handler on that thread, and handlers run one at a time, so the world needs no locks. One thread means a world is as fast as a core, about twelve hundred players on an Apple M4 Pro, and seven hundred on a VPS with two virtual CPUs. And anything slow there holds up the tick for everyone, which is why checking passwords, saving and analytics each went to a program of their own. Ten makes MySQL the source of truth, from episode five. That episode needed a database for the accounts, and looked ahead to items, guilds, friends and trades, data full of relations, where an item mustn't be lost halfway through a trade. The record is fair to MongoDB, which suits a player read and written whole, and has transactions these days. Still, for a game where a lot relates to a lot, I'd pick MySQL again. It's too slow to take each tick's changes, though, so the players reach it through Redis, in record thirteen. Eleven gives logins a server of their own, with passwords hashed by Argon2id. At libsodium's interactive limits, a hash takes about sixty milliseconds, which is longer than a tick. So the login server checks the password, and puts a token in Redis for the client, which works once, within thirty seconds, and the world doesn't see a password at all. The question I'd expect is why not a JSON web token, which the world could check on its own. A token in Redis works once, and we can take it back by deleting it. That bit us in episode thirty-six, when a world's next instance refused the token its players had already used, so a handover issues a token for each move. Thirteen saves the players through Redis, and a saver that takes them on to MySQL. Until episode thirteen, a player was saved as they left, so a crash lost everything since they logged in, and saving each change to MySQL took the tick past its fifty milliseconds at about fifty players. Now, after each tick, the world puts the players who changed into Redis, in one round trip, and the saver takes them on to MySQL in batches, five seconds apart, which is called write-behind. Saving on a thread of its own was turned down, as a crash would lose what's waiting in its queue, which is the problem we started with. So MySQL, and the website's rankings with it, run up to about five seconds behind the game. Fifteen changes the tables through Flyway's migrations, from episode eighteen. Before that, a new column meant wiping the volume, accounts and all, which we got away with while they were test accounts, and can't do to players. A migration that has run stays as it is, and a change goes in a new file, which is the rule we have for published steps, and for these records too. Of the four alternatives, Laravel's migrations are the most tempting to me, as the website is a Laravel app already. But then the website would own the tables our C++ servers rely on, and I want that the other way round.
Networking
12:08 On the network, twelve sends inputs and messages over TCP, and the worlds over UDP. TCP delivers in order, and holds up everything behind a lost packet until it's sent again, and positions don't need that, as the next one is newer anyway. So the world goes over UDP in parts of up to twelve hundred bytes, so that IP doesn't split any of them into fragments. TCP for everything lost to a measurement, which is the kind of reason I trust most. In episode nine, at ten percent loss, TCP couldn't keep up with two hundred clients at all, while UDP stayed within a tick or two of no loss. It leaves us two transports to keep, and a world split into parts and put back together on the client. Fourteen started with tcpdump, which in episode fourteen showed a login going over the network with the password as it was typed. Since then, the TCP connections go through TLS 1.3, with certificates from an authority of our own, which the clients trust, and no other. The worlds over UDP stay plain, which I'm fine with, as it's what each player sees in the game anyway. Let's Encrypt and co can't sign for localhost or the names inside Docker, and as we ship the client anyway, it can carry our own authority. The certificate has to name each host a client connects to, though, and that has bitten us more than once. Seventeen sends each player what's near them, by cells, from episode twenty. Before that, each player got the whole world, so N players meant N worlds of N players each, which grows with the square of the players. Now the server sorts everyone into cells of thirty-two metres, and a player gets their own cell and two each way around it, which is called interest management. This one has numbers too, as the whole world sent each of five hundred players three hundred and seventy-seven kilobytes a second. Within sixty-four metres, with names and levels once a second, each of them got ninety-four. The players in a cell shared their world, until last time, when each client's world became its own.
Running the game
14:08 Running the game starts with record nine: metrics, logs and alerts, through Prometheus, Grafana and Loki. Episode one planned for monitoring from the start, in an open format, so that the game isn't tied to one provider's tools. A cloud provider's own stack, such as CloudWatch, was one alternative, and as each of them integrates with Prometheus anyway, I don't think we gave up anything by passing on it. Alloy does worry me a little, as it reads Docker's socket to collect the logs, and that gives it as much power as root on the machine. Sixteen deploys with Compose to one server, and hands the players over. A deploy sends a commit over SSH, and the server builds the images from the source, tests and all, before anything restarts. A world restarts through its next instance, which takes the players over without them losing the world on their screen. A lot of the platforms that run containers for us don't take UDP, or connections that stay open for hours, and Kubernetes is a lot to look after for one server. With one server, we skip a registry, so each deploy builds the C++ on the cores the game runs on, about fifteen minutes the first time. Eighteen finds the worlds through Consul, HashiCorp's service registry. Each world's tick loop sends a heartbeat, two seconds apart, and ten seconds without one drops the world from the list, so a world whose tick is stuck drops out too. A table in MySQL, with each world's address in it, loses on crashes, as a world that crashes leaves its row behind, and players get sent to a server that's gone. Our Consul is a single server, in memory, so it forgets the worlds when it restarts, and each registers again within two seconds. Nineteen keeps the content as data, in protobuf's text format, with a schema next to each file. The parser refuses a field the schema doesn't have, with its file and line, and the servers, the client and the bots don't start without good content. JSON and YAML are easy to edit, but they lost, as they have no schema our C++ knows, so a misspelt field would quietly fall back to its default. I think that's the right call, as a typo that turns into a default is a miserable bug to track down. It does mean the server's image has to carry the files, which episode twenty-six forgot once, and the server stopped in Compose. And twenty gives the whole game one version, and each episode's code is a minor version, like today's zero point seventy-one. The login server lets a client in when its major and minor version match the servers', as an older client would get in, and then misread the worlds it's sent. So after a deploy that moves the minor version, older clients are turned away at their next login.
Guilds and netcode
16:47 The last four come from the latest episodes, starting with guilds. A guild is the first thing one player changes for others, so twenty-one keeps guilds in MySQL alone, with each change a transaction. Each change after the founding locks the guild's row first, then the member's, so changes to one guild happen one at a time, in that order. A guild kept in Redis, with its players, could be written back stale by any world that had it. I don't love that a guild action runs in the world's tick, which waits for MySQL, up to two seconds for a lock, and that's still a very long tick. Twenty-two, from episode sixty-eight, is numbered inputs and client-side prediction. Until then, a key moved you a round trip later, so at a hundred and fifty milliseconds, you started and stopped walking a beat after your fingers. Now the client walks you with each tick's keys as it sends them, with the library the server walks players with, and when the two disagree, the server wins. Step three of that episode predicted what the server steers too, and each world pulled you back, so step four leaves that to the server. And a step has to come out alike on both sides, to the centimetre, so walking is built without fusing a multiply and an add, and a Mac and Linux round it alike. Twenty-three draws everyone else a hundred milliseconds in the past, between two worlds the client has. Before, each figure chased the newest place it had, so a late or lost world made it stop, and then lurch to catch up. Extrapolation, carrying everyone on from the newest world, didn't get weighed at all, and here it bridges a lost world, for two ticks at most. So everyone else is a tenth of a second behind where the server has them, which I find hard to notice, while a stutter jumps right out. And twenty-four is last time's, which leaves out of each world what hasn't changed, by its pieces' hashes. A piece whose hash hasn't changed since the world the client has whole goes by its id alone, and the client keeps it as it has it. Comparing with that one world alone was turned down, as the client may have had any of the worlds sent since, so a piece that changed and changed back would leave it with the change. Field-by-field deltas, or compressing the world, went unweighed, and I'd expect either to save more on the players who move. A player who walks still goes whole each tick, though, so the saving is in the ones standing about, and the monsters resting.
From now on
19:13 Last, the template, which a new record starts from. The title names the choice, the status starts as accepted, and the context says what forced the choice, and the episode it came up in, with what was measured and where. The decision is what we do, in the present tense, as plainly as the code would say it, with the files, the settings and the numbers, so someone can find it in the repo. Naming them is the part I'd check hardest in a review, as it's what ties the record to the code. Each alternative gets a line, with why it lost, and the consequences are what it costs, what it makes easy, and what bit us later, and where. From now on, each episode that makes a choice like these writes its record, adds it to the index, and supersedes an old one when it changes its mind. And in the top CMake file, Doxygen takes in the decisions folder, after the other pages, so the records are in the API docs too.
Wrap-up
20:09 Today, we took the const off a string in settings, so that the return moves it instead of copying it, as clang-tidy asked. Then the game got a folder of twenty-four decision records, from C++ in episode one to last time's delta worlds, each with what forced the choice, what we picked, what else we weighed and what it costs. A record doesn't change once it's accepted, so the raylib record supersedes the Vulkan one, which keeps its page. And from now on, each episode that makes a choice like these writes its record and adds it to the index.
Playing it
21:32 Let me know in the comments which of these decisions you'd have made differently, and if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.