Posts in Backend (20 found)
The Coder Cafe 4 days ago

Building Barista—Part 2: Formal Verification and TLA+

☕ Welcome to The Coder Cafe! Part 1 of Building Barista covered the architecture. Today, we explore formal verification through a real bug my tests missed. You’ll learn what model checking is, how to read a bit of TLA+, and why it catches the bugs we never think about. I spent a lot of time on formal verification at Google; this time, I pointed it at my own system. Get cozy, grab a coffee, and let’s begin! One Email a Day A quick summary of Barista : it’s a system I built that fetches hundreds of sources, gets a unique prompt per user, and sends that user one email per day with the best sources for them. Making sure Barista sends a single email per user per day is something important to me. If Alice receives the same email twice on a random day, that’s a terrible user experience. As discussed in Part 1 , Barista is a set of independent stages coordinating through Postgres. The last one, , runs every 5 minutes, looks for the users whose send time has passed, and emails each of them the posts picked by the stage. The nominal scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ✅ Barista writes back in Postgres that the email to Alice was sent that day. Now the worst-case scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ❌ Before writing back in Postgres that the email was sent, Barista crashes. The stage starts again and notices an email has to be sent to Alice. Barista calls the email provider again and receives an ACK. ← Duplicate email ✅ Barista writes back in Postgres that the email to Alice was sent that day. How do you prevent that? I picked my email provider for it: Plunk. Why Plunk? Because it accepts an idempotency key. When calling Plunk, I pass a key like : the user and the day. If Plunk receives the same key again, it doesn’t send anything; it replies with a 409. My code reads that 409 as “these posts were already sent” and marks them as sent. No duplicate. It was a conscious decision. Plunk is 10x more expensive per email than AWS SES, which has no idempotency key. I was happy to pay for it. So here was the state: A business decision: no duplicates, even if it costs more. A sound design, with an email provider deduplicating for me. Unit tests, integration tests, end-to-end tests. All green. Great mental model of the code. Pure intellectual control . Now, what if I told you my code had a bug? One that none of my tests caught. I only managed to find it with something called formal verification. Let’s see how. Formal Verification Before becoming an SRE, I worked in Air Traffic Management (I talked about it in Reliability Explained ). It’s a so-called safety-critical domain. You can easily imagine why. In a safety-critical system, green tests aren’t enough. That’s the blind spot of intellectual control: tests only check the scenarios we thought about. And the bugs that hurt are, by definition, the ones we didn’t think about. In domains like this, green tests aren’t the end of the conversation. Some teams go further and prove that certain bugs can’t happen. Airbus, for example, used a static analyzer called Astrée to prove that the flight control software of the A340 and A380 is free of a whole class of runtime errors. So instead of picking scenarios one by one, what if we could check all of them? That’s the idea behind formal verification: describe the system precisely, write down the properties it must respect, and let a tool check that no possible execution breaks them. Note the word: verification . It answers “did we build the thing right?”, meaning does the design respect our properties. Not to be confused with validation : “did we build the right thing?”, meaning are these the properties we actually need. A tool can do the first. The second stays on us. There are several ways to verify a system, from mathematical proofs to running real code on generated inputs. The one I used is model checking . A model checker sees a system as states (a value for every variable) and actions (a step from one state to the next). It starts from the initial state, tries every possible action, then every possible action from each new state, and so on, until it has visited every reachable state. A test follows one path. A model checker walks all of them. That’s why it finds bugs nobody writes a test for. AWS described it in 2015, in a paper on how they use formal methods: one of their DynamoDB bugs had survived design reviews, code reviews, and testing. The shortest sequence of events to trigger it was 35 steps long. At each state, the model checker checks our properties. They come in two flavors: Safety : Something bad never happens (e.g., Alice never receives the same email twice) Liveness : Something good eventually happens (e.g., Alice eventually receives her daily email) When a property breaks, we get a counterexample : the exact sequence of steps that led there. The model checker I used is TLC. It reads models written in TLA+, a language created by Leslie Lamport to describe a system as states and actions. In other words: we describe the system in TLA+, and TLC explores every state it can reach. A TLA+ spec doesn’t look like code. There are no instructions executed one after the other. Instead, each action is a formula that says two things: when the step is allowed (a condition on the current state), and what the state looks like after it (the values in the next state). TLC then tries every allowed action, in every possible order. A few symbols are enough to follow the examples below: means “is defined as” is the value of in the next state and mean “for all” and “there exists” Let’s see it on a simple example. Imagine a cafe with one croissant left and two baristas. When a customer asks for a croissant, a barista does two things: first, they check the display case to see if there’s one left; then, they sell it. The property we want is a safety one (something bad never happens): the cafe never sells a croissant it doesn’t have. In other words, the stock never goes below zero. To model this cafe, we need two variables: : how many croissants are left. It starts at 1. : where each barista is. Each one starts , moves to after checking, and ends . Now, the two actions. The first one is checking the display case: The first two lines are conditions: can only happen if barista is idle and there’s a croissant left. The last two lines describe the next state: is now selling ( means “every other barista stays where they are”), and the stock stays the same. The second action is selling: And the property, written as an invariant that must hold in every state: That’s the whole model. TLC starts from the initial state (one croissant, two idle baristas) and tries every action, in every possible order. In most orders, everything is fine. For example, barista 1 checks and sells, then barista 2 can’t check anymore because the stock is zero. But TLC finds one order that breaks the invariant: Both baristas looked at the display case before either one sold. Both saw a croissant. Both sold it. That’s how to read a counterexample: find the step where it broke (5), then walk back to the decision that made it inevitable (3). The fix is to make checking and selling a single action, so nobody can slip in between. Re-run TLC, and it explores every state without finding a violation. In a cafe, we can merge two steps. Across a network call and a database write, we can’t, and that’s exactly why idempotency keys exist. Now, let’s do the same with Barista. Back to Barista. Years after leaving Air Traffic Management, I wondered: what if I applied the same rigor here? So I wrote a TLA+ spec of the stage. The model was tiny: one user, two posts, a clock with eight slots per day, and two days. The key idea is that it tracks two things separately: what was really delivered to the user, and what Barista believes was delivered. If Barista works, both always agree. The full spec also has a few actions I’m leaving out here: the clock ticks, Rank picks new posts, and moves the next send time forward. Here are the variables (simplified): : the clock. : when user ’s next email is due. : the posts picked for ’s next email. : the idempotency keys Plunk has already seen. : the list of emails really delivered. The truth. : the posts Barista has marked as sent to . What Barista believes. And a simplified version of the action at the time: A few new pieces: defines a local name (here, the key). is a pair, our . adds to a set, and adds to the end of a list. And is a record: an email to containing these posts. Read it line by line. can only run once the send time has passed. If Plunk already knows the key, it replies with a 409 and nothing is delivered. Otherwise, the email goes out. Either way, Plunk remembers the key, and Barista marks the posts as sent. That last line is the one to watch. The real action can also end badly: Plunk delivers the email, then Barista crashes before recording anything. TLC tries that outcome too. Now the property, in the same spirit as the cafe’s : In plain English: Barista’s belief must match the truth. If a post is marked as sent, an email really contained it. I ran TLC. Guess what? Despite all the tests, despite the idempotency key I was paying 10x for, it failed on the first run . Every configuration failed, even the simplest one: no crash, no settings change. Here’s one of the counterexamples, in real times. Alice gets her email at 22:00 UTC: An outage on May 20 eats Alice’s May 21 email. The catch-up send at 01:00 UTC uses key , so the regular send at 22:00 gets a 409, and its posts are marked as sent without being delivered. Alice never gets her May 21 email. Its posts are marked as sent, so Barista will never offer them again. No error, no alert. And it happens 21 hours after everything recovered. The fun part is that I never modeled an outage. Nothing in the spec says Barista can be down. But nothing forces to run on time either: in TLA+, the clock is just another action, and TLC is free to let it tick while waits. An outage, a slow deploy, a job stuck behind another one: for the model, it’s all the same. TLC tried every possible delay and found the one crossing midnight. So what went wrong? Plunk did exactly what it promised. A 409 doesn’t mean “these posts were sent.” It means “something was already sent under this key.” My key was the day of the attempt, not the day the email was for. As long as a send ran on the day it was due, it didn’t matter. The moment one slipped past midnight, it did. Should Barista skip the catch-up, then? No. Alice should still get her May 20 email. The catch-up was right; my reading of the 409 was wrong. Ironically, I was obsessed with sending too many emails, and the very thing I was paying 10x for made me send too few, silently. Would my tests have caught it? Honestly, no. I tested a crash after the ACK, and the idempotency key handled it. I would never have written a test where runs late, past midnight UTC, followed by a regular send the next evening. And that was exactly my fear in the first place. The fix? One key per email instead of one per day. I re-ran TLC. Green. In December 2025, Martin Kleppmann, the author of Designing Data-Intensive Applications , published a post with a bold prediction: AI will make formal verification go mainstream . His argument is mostly about cost. Formal verification has always been expensive. Proving that seL4, an OS kernel of about 8,700 lines of C, was correct took around 20 person-years. For most systems, a bug was cheaper than the proof that would have prevented it. But coding agents are getting good at writing proofs. And a wrong proof isn’t dangerous: the checker rejects it, and the agent tries again. One of the issues with TLA+ has always been making sure the spec is accurate. A TLA+ spec is a model, and a model is only as good as its abstraction. TLC checks the spec, not the code. The hard part is making sure the spec describes what the code actually does. But with the rise of coding agents, especially over the last few months, I feel like this gap is shrinking. An agent can read the code and draft the spec, keep both in sync when the code changes, and turn a counterexample into a failing test against the real code. At Google, I spent a lot of time exploring formal verification, especially on convoluted logic: loops with several paths, retries, error codes. On many occasions, I found bugs despite significant test coverage. Back then, though, writing and maintaining a spec was a real investment, so it was reserved for the parts that truly justified it. That’s what’s changing. When a spec costs an afternoon instead of weeks, the question is no longer “is this part critical enough to deserve a spec?” It becomes “why not?” Does it mean software will be bug-free? No. As Kleppmann also points out, the hard part moves to the specification itself: are we checking the properties we actually care about? That’s the validation question from earlier. But think about what it took to find Barista’s bug: a property of a few lines, and a tool patient enough to try every delay, every order, every midnight. Now extend that. Maybe that’s what software engineering becomes: less time on how the code achieves something, more time on what must hold no matter what. Alice never receives the same email twice. Alice eventually receives her daily email. We write those down; agents write the code and the spec; tools check that the properties hold. Kleppmann compares it to compilers: we don’t read the machine code they produce, and maybe one day, we won’t read the code agents produce either. Will we get there? I don’t know. But it might be worth exploring in your own system: write down its invariants, and see whether a model can show you where they break. If you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Resources Sources How Amazon Web Services Uses Formal Methods, Newcombe et al., CACM, 2015 Systems Correctness Practices at AWS, Brooker and Desai, ACM Queue, 2024 The Astrée Static Analyzer Prediction: AI will make formal verification go mainstream How we continuously validate formal specifications in production - Datadog One Email a Day A quick summary of Barista : it’s a system I built that fetches hundreds of sources, gets a unique prompt per user, and sends that user one email per day with the best sources for them. Making sure Barista sends a single email per user per day is something important to me. If Alice receives the same email twice on a random day, that’s a terrible user experience. As discussed in Part 1 , Barista is a set of independent stages coordinating through Postgres. The last one, , runs every 5 minutes, looks for the users whose send time has passed, and emails each of them the posts picked by the stage. The nominal scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ✅ Barista writes back in Postgres that the email to Alice was sent that day. The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ❌ Before writing back in Postgres that the email was sent, Barista crashes. The stage starts again and notices an email has to be sent to Alice. Barista calls the email provider again and receives an ACK. ← Duplicate email ✅ Barista writes back in Postgres that the email to Alice was sent that day. A business decision: no duplicates, even if it costs more. A sound design, with an email provider deduplicating for me. Unit tests, integration tests, end-to-end tests. All green. Safety : Something bad never happens (e.g., Alice never receives the same email twice) Liveness : Something good eventually happens (e.g., Alice eventually receives her daily email) means “is defined as” is the value of in the next state and mean “for all” and “there exists” : how many croissants are left. It starts at 1. : where each barista is. Each one starts , moves to after checking, and ends . : the clock. : when user ’s next email is due. : the posts picked for ’s next email. : the idempotency keys Plunk has already seen. : the list of emails really delivered. The truth. : the posts Barista has marked as sent to . What Barista believes. An outage on May 20 eats Alice’s May 21 email. The catch-up send at 01:00 UTC uses key , so the regular send at 22:00 gets a 409, and its posts are marked as sent without being delivered. Alice never gets her May 21 email. Its posts are marked as sent, so Barista will never offer them again. No error, no alert. And it happens 21 hours after everything recovered. The fun part is that I never modeled an outage. Nothing in the spec says Barista can be down. But nothing forces to run on time either: in TLA+, the clock is just another action, and TLC is free to let it tick while waits. An outage, a slow deploy, a job stuck behind another one: for the model, it’s all the same. TLC tried every possible delay and found the one crossing midnight. So what went wrong? Plunk did exactly what it promised. A 409 doesn’t mean “these posts were sent.” It means “something was already sent under this key.” My key was the day of the attempt, not the day the email was for. As long as a send ran on the day it was due, it didn’t matter. The moment one slipped past midnight, it did. Should Barista skip the catch-up, then? No. Alice should still get her May 20 email. The catch-up was right; my reading of the 409 was wrong. Ironically, I was obsessed with sending too many emails, and the very thing I was paying 10x for made me send too few, silently. Would my tests have caught it? Honestly, no. I tested a crash after the ACK, and the idempotency key handled it. I would never have written a test where runs late, past midnight UTC, followed by a regular send the next evening. And that was exactly my fear in the first place. The fix? One key per email instead of one per day. I re-ran TLC. Green. The Future of Software Engineering? In December 2025, Martin Kleppmann, the author of Designing Data-Intensive Applications , published a post with a bold prediction: AI will make formal verification go mainstream . His argument is mostly about cost. Formal verification has always been expensive. Proving that seL4, an OS kernel of about 8,700 lines of C, was correct took around 20 person-years. For most systems, a bug was cheaper than the proof that would have prevented it. But coding agents are getting good at writing proofs. And a wrong proof isn’t dangerous: the checker rejects it, and the agent tries again. One of the issues with TLA+ has always been making sure the spec is accurate. A TLA+ spec is a model, and a model is only as good as its abstraction. TLC checks the spec, not the code. The hard part is making sure the spec describes what the code actually does. But with the rise of coding agents, especially over the last few months, I feel like this gap is shrinking. An agent can read the code and draft the spec, keep both in sync when the code changes, and turn a counterexample into a failing test against the real code. At Google, I spent a lot of time exploring formal verification, especially on convoluted logic: loops with several paths, retries, error codes. On many occasions, I found bugs despite significant test coverage. Back then, though, writing and maintaining a spec was a real investment, so it was reserved for the parts that truly justified it. That’s what’s changing. When a spec costs an afternoon instead of weeks, the question is no longer “is this part critical enough to deserve a spec?” It becomes “why not?” Does it mean software will be bug-free? No. As Kleppmann also points out, the hard part moves to the specification itself: are we checking the properties we actually care about? That’s the validation question from earlier. But think about what it took to find Barista’s bug: a property of a few lines, and a tool patient enough to try every delay, every order, every midnight. Now extend that. Maybe that’s what software engineering becomes: less time on how the code achieves something, more time on what must hold no matter what. Alice never receives the same email twice. Alice eventually receives her daily email. We write those down; agents write the code and the spec; tools check that the properties hold. Kleppmann compares it to compilers: we don’t read the machine code they produce, and maybe one day, we won’t read the code agents produce either. Will we get there? I don’t know. But it might be worth exploring in your own system: write down its invariants, and see whether a model can show you where they break. If you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Resources Sources How Amazon Web Services Uses Formal Methods, Newcombe et al., CACM, 2015 Systems Correctness Practices at AWS, Brooker and Desai, ACM Queue, 2024 The Astrée Static Analyzer Prediction: AI will make formal verification go mainstream How we continuously validate formal specifications in production - Datadog

0 views
Martin Fowler 6 days ago

Long-horizon agents and durable execution

Long-horizon agents can automate complex tasks that take days or weeks to complete and involve multiple exchanges with people and external systems. Many things can go wrong during this time, including process crashes, network failures, and unanticipated real-world behavior. Kiran Prakash explains durable execution: an emerging pattern that helps agents recover from these failures and move towards their goal. In this programming model, the runtime keeps a record of the result of each step that interacts with the outside world so that, when a failure occurs, the program runs again, completed steps are skipped, and the program's state is rebuilt from the record.

0 views
Sean Goedecke 1 weeks ago

A database is a store for global variables

Databases are for storing global variables. We usually call them “rows” or “records” instead, but they’re definitionally global variables: any part of your program can read or write them. Isn’t this kind of weird? It’s common programming advice that global variables are bad, and yet many elegant programs rely on databases. Either the common advice is wrong, or there’s something special about databases that makes them the exception to the rule. What’s so bad about global variables? Here’s the two main 1 reasons, in my view: Both of these apply to databases. Any part of your program that makes a query can send and receive data from any other part of your program. In practice this happens all the time: one function will save some data on a record, and another one will check for it. And if you haven’t seen bugs where some piece of code makes some incorrect expectation about the shape 2 of a database column, you haven’t been working on web systems for long enough. So why aren’t database-backed apps in terrible architectural shape? In the rest of this post I’ll consider some options. First, we could bite the bullet : maybe all database-backed apps really are a mess . This is surprisingly plausible. When I think about the systems I’ve worked on that haven’t involved a database, they’re usually much cleaner and more elegant. If managing state is the hardest thing about designing software — and I think it is — then systems that manage less state are going to be better-designed. However, this doesn’t explain everything. Database-backed apps aren’t that bad, and even in database-backed apps, we try to avoid introducing regular global variables 3 , so in practice we treat global variables as worse. Second, we could say that databases offer ACID guarantees that mitigate the damage of global variables . Unlike regular global variables, databases offer a consistent view of state and the ability to atomically change multiple pieces of state together. I don’t really buy this. The problem with global variables is not just that they can get out of sync, it’s that they exist at all. If you think this is the difference, you are committed to thinking 4 that if you stick a mutex around a global variable then it suddenly becomes acceptable. Third, we could say that databases are more explicit . Mutating or reading a global variable looks like ordinary code, but database queries need some connection object to be passed in and some query function to be invoked. When you’re scanning through code, you can see where the database queries are at a glance 5 . Not so for global variables. This does actually kind of mitigate the implicit-coupling problem. Maybe regular global variables would be better if you had to set and get them with long, involved function calls. Fourth, we could say that databases are less flexible . A global variable could store anything : a function, a class, an image, and so on. A database just stores data . I can buy this explanation for untyped languages. Global Ruby variables that could be reassigned from a string to a hash table are far more terrifying than a “global” database column that could change from one string to another string. But since the advice to avoid global variables applies to typed languages as well, I don’t think this could be the reason why databases are better. Fifth, we could say that we know how to use databases . For instance, whenever I read from a database, I reflexively check the type of the column so that my code doesn’t make assumptions that aren’t guaranteed by the database. There are use-cases that I would never even consider using a database for (e.g. to track a counter in a loop, or to store the name of the file where my config is stored). In other words, we have norms and customs 6 around using databases that minimize a lot of the damage that global variables can cause. There’s nothing inherent about databases that make them better, it’s just how we use them in practice. Overall I think the third and fifth reasons are most convincing: databases are better because they’re more explicit and because we only tend to use them for a limited set of purposes. It’s interesting to note that these reasons are contingent , not inherent. A codebase which had conventions around global variable use 7 could also fulfil these conditions. Would this make global variables fine, or at least no worse than a database? I think so. I don’t recommend you go out and start putting global variables in your programs. It’s more interesting to note the meta-point here: that two pieces of common software engineering dogma — avoid global variables and use a database for state — are partially inconsistent. Most software design knowledge is still just a pile of loose heuristics. I don’t really know how to build software and you don’t either . As I’ve written about before , we should therefore all be very suspicious of engineers who appeal to “best practice” without being able to give concrete reasons, even in cases as obvious as “global variables are bad”. For instance, concerns about readability and tracing follow from the first reason. I don’t really buy reasons like “it’s not thread-safe” or “global variables might shadow local variables”: any architectural problem that can be trivially solved with a mutex or a linter is not a real problem. For instance, that a string supports 4-byte UTF-8, or that a column can/can’t be NULL. You could say we avoid introducing global variables because databases are essential and global variables are not. In theory you could replace any global variable by threading a local variable through, but you do need a database if you’ve got gigabytes of structured data to manage. However, that doesn’t explain why database-backed apps still tend to be better-designed than apps with many global variables. I’m not saying this is necessarily wrong. The argument would go something like “well, if you implement a simple in-memory database for your global variables, that is better!” This is only sort of true. If you’re designing a system, you’d be well-advised to make it as true as you can. While I love Rails, my main beef with ActiveRecord is that it makes queries invisible. To be fair, some of these are guaranteed by the fact that the database exists over the network. Plus types, probably, and concurrency controls if we’re not in a single-threaded language. They allow any part of your program to implicitly send data to any other part instead of passing it around via function signatures They couple different parts of your program: if one part depends on a variable having some value, any other part can break it For instance, concerns about readability and tracing follow from the first reason. I don’t really buy reasons like “it’s not thread-safe” or “global variables might shadow local variables”: any architectural problem that can be trivially solved with a mutex or a linter is not a real problem. ↩ For instance, that a string supports 4-byte UTF-8, or that a column can/can’t be NULL. ↩ You could say we avoid introducing global variables because databases are essential and global variables are not. In theory you could replace any global variable by threading a local variable through, but you do need a database if you’ve got gigabytes of structured data to manage. However, that doesn’t explain why database-backed apps still tend to be better-designed than apps with many global variables. ↩ I’m not saying this is necessarily wrong. The argument would go something like “well, if you implement a simple in-memory database for your global variables, that is better!” ↩ This is only sort of true. If you’re designing a system, you’d be well-advised to make it as true as you can. While I love Rails, my main beef with ActiveRecord is that it makes queries invisible. ↩ To be fair, some of these are guaranteed by the fact that the database exists over the network. ↩ Plus types, probably, and concurrency controls if we’re not in a single-threaded language. ↩

0 views
The Coder Cafe 1 weeks ago

Building Barista—Part 1

☕ Welcome to The Coder Cafe! A few weeks ago, I built Barista : describe what you like to read in your own words, and every day it emails you a few posts worth your time, picked from hundreds of engineering blogs, Hacker News, Lobsters, and arXiv. This is the first part of a series on how it works: not a tutorial, but the decisions behind a real system I built and run in production. This week, we explore its architecture. You’ll see how embeddings turn meaning into geometry, how a decision model judges what’s actually worth your time, and how a single Postgres can be a queue, a scheduler, and a vector database, with no message broker in sight. Get cozy, grab a coffee, and let’s begin! Problem When I started as a software engineer (10+ years ago), my daily routine was to go through Twitter and read every single post from the people I followed since the day before. I could also consistently read every post in my small RSS feed. I was happy with my tech watch, and I was consistent. Fast forward to today: there’s been an absolute explosion of information . Twitter now defaults to “For you”, so my feed is infinite. Meanwhile, my RSS reader currently shows 1,457 unread posts. There’s just too much, all the time. I created The Coder Cafe to solve this exact problem. My initial idea was to write one post a day, so that readers could learn one thing every day. The original newsletter’s description said it all: Feeling overwhelmed by the endless stream of tech content? At The Coder Cafe, we serve timeless concepts with your coffee, every day. Then things changed (👶), and I couldn’t keep up with one post a day anymore, so I switched to a more sustainable pace. In doing so, I lost the initial premise: helping people read less while still reading quality content. I’d given up on that idea until… recently. A few weeks ago, I started looking for ways to improve my tech watch (yet again). One of the tools I found was devdigest.io . However, its sign-up page looked like this, asking me which topic I wanted to subscribe to: I don’t know about you, but for me it doesn’t work. What if, instead of “Software engineering”, I want to be more specific and say I love this or that language? Or that I love posts about testing? There was no way to do that. I kept looking, but never found what I wanted. So I started building it . I originally built Barista for myself. The initial idea was simple: let it fetch lots of content from the web. Then I would just give it a prompt describing my interests, in my own words. For example: I’m a senior SRE and Go engineer. Show me deep, technical content on: Programming: programming concepts, unit tests, etc. Go: performance, profiling, latency, runtime internals Systems fundamentals: Linux internals (processes, memory, I/O), databases, Postgres, etc. Kubernetes internals: controllers/operators, reconciliation, kube-apiserver, edge and fleet-scale rollouts Reliability & SRE: safe rollouts, disruption management, resiliency, incident analysis, etc. Prefer: first-principles explanations, architecture write-ups, benchmarks with data, lessons from production. Skip: beginner tutorials, listicles, framework hype, marketing posts, generic AI news. From there, the system filters out everything outside my interests, plus spam, low-quality content, etc. Then, it sends me one email a day with a few posts. After using it for a while, I thought: if I enjoy it this much, why not turn it into a product and see if others like it too? Want to see what it picks for you? Write your own brief , and your first email lands in seconds, no account needed. In this first part, let’s look at how it works under the hood and at the main decisions I made along the way. At a high level, Barista is built as a pipeline: It has two halves, and they work very differently. The left half is about posts . Ingest, fetch, classify, and embed run all day long, and each post goes through them exactly once, no matter who ends up reading it. A post is downloaded once, classified once, and embedded once, whether it ends up in zero inboxes or a hundred. Each stage hands posts to the next through a queue. The right half is about users . Match, rank, and send run once a day per user, and there’s no queue here: what drives them is the clock. Each user picks a send hour, and the system works back from it. Match runs two hours before, rank one hour before, and send right on time. The stages are the following: Ingest: Polls the sources and records each new post’s URL. A URL it has already seen is skipped, so each post enters Barista only once. Fetch: Downloads each post’s page and extracts its title, author, date, and text. A post is dropped if the page can’t be read, isn’t in English, or is too short, for example. It also respects and never hits the same site more than once every couple of seconds. Classify: Asks an LLM what the post is: its topic, how deep and how good it is, and whether it’s spam or a paywall teaser. Anything off-topic, spammy, or low quality is dropped here. Embed: Turns the post into a vector, a list of numbers capturing what it’s about (more on that below). From here, the post becomes a candidate for every user. Match: Two hours before a user’s send time, it takes the user’s interests (embedded into the same space when they saved them) and finds the recent posts whose vectors are closest. The closest ones become that user’s backlog. Rank: An hour before send time, an LLM grades how well each new post in the backlog fits the user’s interests, taking their recent votes into account. The best-graded posts are picked for the day. Send: At the user’s chosen hour, sends the email with the day’s picks, each with “More like this” and “Less like this” buttons. That feedback flows back into future rank runs. So how do these stages talk to each other? Through Postgres. When we hear “a pipeline of stages”, the reflex might be to reach for a message broker: Kafka, RabbitMQ, maybe Redis streams. That was my reflex too. Yet going against my instincts, Barista doesn’t have one: every arrow in the diagram is Postgres. Queues are tables. In the per-post half, each stage drains a table filled by the previous one. Ingest writes new URLs into , fetch drains it and writes into , and so on down the line. Several workers process a stage in parallel, and each claims its next row like this: locks the row so no other worker can take it. means the other workers don’t wait on it; they move on to the next free row. That’s a work queue in one SQL clause. Retries and dead letters are just data too. A row that fails gets a timestamp and is retried later, with a backoff that starts at 5 minutes and doubles up to 6 hours. After 10 failures, about a day in, it’s moved into a table with the reason, so one broken page never blocks the posts behind it. Schedules are columns. The per-user half keeps its schedule on the user row, in three timestamps: , and . Each stage picks up the users whose timestamp is due, does its work, and moves its timestamp to the next day. Each stage also waits for the previous one: rank only handles a user once match has moved that user’s into the future, meaning “match is done for today”. So there’s no scheduler service or workflow engine to run. Each stage just queries for the users who are due. Each stage is a short-lived job. A stage is a small program started on a cron. It wakes up, processes whatever is due, and exits. Nothing runs, and nothing costs anything, between runs. So why not Kafka? In the end, running a personal project is also about being pragmatic, and three reasons won me over. First, scale. Barista processes a few hundred posts a day, not millions of events per second. Kafka shines at throughput I simply don’t have, and it would be one more system to run, monitor, and pay for, next to a database I need anyway. Second, and that’s the reason I care about most: the queue and the data live in the same transaction. When fetch processes a post, claiming the row, saving the extracted text, and queuing the post for the next stage all happen in one transaction. Either everything commits, or nothing does. If the job crashes halfway, the transaction rolls back, the row is unlocked, and the next run picks it up as if nothing happened. With a broker, that’s much harder. We write to the database, and we acknowledge a message (or publish one), two systems that can’t commit together. Crash between the two, and we either lose work or do it twice. Solving that properly is a whole topic on its own (the transactional outbox pattern exists precisely for this). With everything in Postgres, the problem just doesn’t exist (or barely). Third, everything is queryable. A post’s whole journey, from the URL ingest found to the email it ended up in, is a set of rows. For example, “Why didn’t this post reach anyone?” becomes an SQL query. All of this runs on a single Cloud SQL , Google’s smallest tier: a shared CPU and 614 MB of memory, for about $8 a month. Will it be enough forever? Probably not. But when it isn’t anymore, I’ll have a good problem, and I’ll know exactly which part to move out first. Choosing Postgres is not entirely free, though. In some stages, that transaction stays open during the network call (downloading a page, asking the LLM), which holds a lock and a database connection the whole time. It’s a tradeoff I’ll come back to in a future post, because it bit me once. Postgres has one more role I haven’t mentioned yet: it’s also my vector database. Postgres has one more job, and it’s the one that makes Barista work: finding the posts that fit what a user wrote in plain English. Here’s the problem. On one side, thousands of posts. On the other, a user who wrote a paragraph about what they like. How do we match the two? The naive answer is keyword search: look for posts containing “Go”, “Kubernetes”, “Postgres”. It breaks quickly. A great post about MVCC might never write “Postgres” in its title. A post that mentions “Go” five times might be about the board game. Keywords capture words, not meaning. That’s what embeddings solve. An embedding is a list of numbers representing a piece of text. In Barista, each post becomes a list of 1,024 numbers, computed by an embedding model from the post’s title and text. On their own, those numbers mean nothing to a human. There’s no “number 42 means Postgres”. What matters is where the list sits compared to the others. Think of each list as the coordinates of a point, not on a 2D map but in a space with 1,024 dimensions. The model was trained on huge amounts of text with one goal: texts that mean similar things should end up close to each other in that space, and unrelated texts far apart. So a post on how Postgres implements MVCC and a post on transaction isolation levels land near each other, even if they barely share a word. And the post about Go the board game lands far from the one about goroutines, even though both say “Go” all the time. “Close” is measured with cosine distance. Roughly, it’s the angle between two vectors: a small angle means similar meaning, a large one means unrelated. Now here’s the trick: your interests are embedded too, into the same space. When you write “I love posts about Go performance, profiling and runtime internals”, that sentence becomes a point, just like the posts. Finding posts for you becomes a geometry problem: which posts are the closest points to your interests? Two details make it work well in practice: Posts and interests aren’t embedded the same way. A post is embedded as a document ; the interests as a query . A two-line description of what you want doesn’t look like the long article that answers it, and embedding models handle this asymmetric case explicitly. A prompt with several interests is split. My own prompt covers Go, Linux internals, Kubernetes, and reliability. As a single vector, it would land somewhere in the middle of all of them, close to none. So Barista has an LLM split the prompt into separate interests, embeds each one, and looks for posts close to any of them. This is where pgvector comes in. It’s a Postgres extension that adds a column type and distance operators. Embeddings are stored in a plain table, next to everything else, and finding the closest posts is a SQL query. Simplified: is pgvector’s cosine distance operator. And that query is why I didn’t reach for a dedicated vector database. The search also has to filter. I want the closest vectors among posts from the last 30 days, never offered to this user before, not from a site they blocked, and preferably one per site. Every one of those filters is regular data that already lives in Postgres. With a separate vector store, I would have to copy that data there and keep it in sync, or search broadly and filter afterwards. With pgvector, it’s one clause. Embeddings tell Barista what a post is roughly about. They can’t tell whether it’s any good, whether it’s spam, or whether it’s actually what you want to read today. For that, Barista uses a decision model: Jev by TypeSafe . It reads natural language, but it doesn’t write any. It only answers questions. So instead of a prompt and some free-form text back, we send it two things: A state: The data to judge, as JSON Questions: Each with a type that defines the shape of the answer There are three question types: Choice: Pick one option from a list we provide Score: Pick a level on a scale we describe (2 to 10 ordered levels) Noul: A yes/no question, answered as a probability And the answers come back typed too. So I can skip the “ please answer in valid JSON ”, the regex on the output, and the retry when the model decides to add a friendly sentence first. Another detail I love: a score answer is probability-weighted, so instead of 2, we get something like 2.37. That’s a lot more useful when we need to compare and threshold things. Barista asks Jev questions in two places. Every post that gets through fetch is sent to Jev once, with multiple questions: Domain ( choice ): What is the primary domain of this post? Depth ( score ): How technically deep is this post? Quality ( score ): How well-written and substantive is this post? Paywall teaser ( noul ): Is this a paywall teaser? Spam ( noul ): Is this spam? The rules are implemented in plain Go. For example, spam probability above 0.7? Dropped. The point is to filter as early as possible. A post dropped here costs a fraction of a cent once, and then never costs anything again: no embedding, no grading, for any user. And the answers are stored, so the topic, depth and quality feed the later stages. This is where Jev does the real work. Match gave each user a short list of candidates, found cheaply with embeddings. Now Jev grades each one with a single question, “How well does this post fit the user’s interests?”, on four levels: Poor fit: largely unrelated to the user’s stated interest Weak fit: tangentially related but not a strong match Good fit: clearly matches the user’s stated interest Excellent fit: a standout match, exactly what the user is looking for The state holds the user’s prompt, the candidate (title, description, the opening of its text, plus classify’s topic, depth, and quality), and the user’s last five days of 👍/👎 votes, with comments if they left any. So “fewer AI posts, please” really does change what gets picked. A design decision I didn’t expect to make: I grade each candidate in its own request. My first version sent the whole backlog in one request and asked Jev to grade everything at once. It was cheaper in calls, but the grades were unstable. Jev judges each question against the whole state, so the other candidates in the request acted as distractors and shifted each other’s grades. The same post could be “Good” on Monday and “Weak” on Tuesday, just because of its neighbors. Graded alone, a post’s grade only depends on the post and on you. That makes it stable, and since it’s stable, it’s worth keeping. Each grade is stored and reused for as long as the post stays in your backlog. A post is only graded again if you leave new feedback, since your votes might change the verdict. Then picking is simple: the best-graded posts win. For a small email, a post needs at least “Good” to be picked. The one exception is the day’s best candidate, so you always get at least one post. Barista would rather send you two great posts than pad the email with a third mediocre one. If we step back, the split looks like this: Match (embeddings): from thousands of posts to a short list. Cheap, fast, approximate Rank (Jev): from that short list to the few posts in your email. Slower, costs money per call, precise To summarize: Embeddings answer “what is this roughly about?” Jev answers “is this actually good for you ?” So far, this sounds like a reasonable little system. Here’s what I left out. Barista also has: About 23,000 lines of Go, and 31,000 more lines of tests (yes, more test code than code). 22 alerts and nearly 50 custom metrics. An AI on-caller to triage alerts. A TLA+ spec, model-checked, to make sure nobody gets two emails a day. A randomized simulation that replays days of pipeline life on a fake clock. A chaos test that throws 1,000 simultaneous users at a database the size of a Raspberry Pi. All of that for… currently 5 users . Over-engineered? Probably 😁. But it makes for good material for a series. Each item on that list comes with a story, and some of them surprised me. Starting next week with the first one: how I tried to prove that nobody gets two emails a day, and my test failed on its very first run. In the meantime, if you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Problem When I started as a software engineer (10+ years ago), my daily routine was to go through Twitter and read every single post from the people I followed since the day before. I could also consistently read every post in my small RSS feed. I was happy with my tech watch, and I was consistent. Fast forward to today: there’s been an absolute explosion of information . Twitter now defaults to “For you”, so my feed is infinite. Meanwhile, my RSS reader currently shows 1,457 unread posts. There’s just too much, all the time. I created The Coder Cafe to solve this exact problem. My initial idea was to write one post a day, so that readers could learn one thing every day. The original newsletter’s description said it all: Feeling overwhelmed by the endless stream of tech content? At The Coder Cafe, we serve timeless concepts with your coffee, every day. Then things changed (👶), and I couldn’t keep up with one post a day anymore, so I switched to a more sustainable pace. In doing so, I lost the initial premise: helping people read less while still reading quality content. I’d given up on that idea until… recently. A few weeks ago, I started looking for ways to improve my tech watch (yet again). One of the tools I found was devdigest.io . However, its sign-up page looked like this, asking me which topic I wanted to subscribe to: I don’t know about you, but for me it doesn’t work. What if, instead of “Software engineering”, I want to be more specific and say I love this or that language? Or that I love posts about testing? There was no way to do that. I kept looking, but never found what I wanted. So I started building it . Introducing Barista I originally built Barista for myself. The initial idea was simple: let it fetch lots of content from the web. Then I would just give it a prompt describing my interests, in my own words. For example: I’m a senior SRE and Go engineer. Show me deep, technical content on: Programming: programming concepts, unit tests, etc. Go: performance, profiling, latency, runtime internals Systems fundamentals: Linux internals (processes, memory, I/O), databases, Postgres, etc. Kubernetes internals: controllers/operators, reconciliation, kube-apiserver, edge and fleet-scale rollouts Reliability & SRE: safe rollouts, disruption management, resiliency, incident analysis, etc. After using it for a while, I thought: if I enjoy it this much, why not turn it into a product and see if others like it too? Want to see what it picks for you? Write your own brief , and your first email lands in seconds, no account needed. In this first part, let’s look at how it works under the hood and at the main decisions I made along the way. Pipeline-Based Architecture At a high level, Barista is built as a pipeline: It has two halves, and they work very differently. The left half is about posts . Ingest, fetch, classify, and embed run all day long, and each post goes through them exactly once, no matter who ends up reading it. A post is downloaded once, classified once, and embedded once, whether it ends up in zero inboxes or a hundred. Each stage hands posts to the next through a queue. The right half is about users . Match, rank, and send run once a day per user, and there’s no queue here: what drives them is the clock. Each user picks a send hour, and the system works back from it. Match runs two hours before, rank one hour before, and send right on time. Ingest: Polls the sources and records each new post’s URL. A URL it has already seen is skipped, so each post enters Barista only once. Fetch: Downloads each post’s page and extracts its title, author, date, and text. A post is dropped if the page can’t be read, isn’t in English, or is too short, for example. It also respects and never hits the same site more than once every couple of seconds. Classify: Asks an LLM what the post is: its topic, how deep and how good it is, and whether it’s spam or a paywall teaser. Anything off-topic, spammy, or low quality is dropped here. Embed: Turns the post into a vector, a list of numbers capturing what it’s about (more on that below). From here, the post becomes a candidate for every user. Match: Two hours before a user’s send time, it takes the user’s interests (embedded into the same space when they saved them) and finds the recent posts whose vectors are closest. The closest ones become that user’s backlog. Rank: An hour before send time, an LLM grades how well each new post in the backlog fits the user’s interests, taking their recent votes into account. The best-graded posts are picked for the day. Send: At the user’s chosen hour, sends the email with the day’s picks, each with “More like this” and “Less like this” buttons. That feedback flows back into future rank runs. First, scale. Barista processes a few hundred posts a day, not millions of events per second. Kafka shines at throughput I simply don’t have, and it would be one more system to run, monitor, and pay for, next to a database I need anyway. Second, and that’s the reason I care about most: the queue and the data live in the same transaction. When fetch processes a post, claiming the row, saving the extracted text, and queuing the post for the next stage all happen in one transaction. Either everything commits, or nothing does. If the job crashes halfway, the transaction rolls back, the row is unlocked, and the next run picks it up as if nothing happened. With a broker, that’s much harder. We write to the database, and we acknowledge a message (or publish one), two systems that can’t commit together. Crash between the two, and we either lose work or do it twice. Solving that properly is a whole topic on its own (the transactional outbox pattern exists precisely for this). With everything in Postgres, the problem just doesn’t exist (or barely). Third, everything is queryable. A post’s whole journey, from the URL ingest found to the email it ended up in, is a set of rows. For example, “Why didn’t this post reach anyone?” becomes an SQL query. Posts and interests aren’t embedded the same way. A post is embedded as a document ; the interests as a query . A two-line description of what you want doesn’t look like the long article that answers it, and embedding models handle this asymmetric case explicitly. A prompt with several interests is split. My own prompt covers Go, Linux internals, Kubernetes, and reliability. As a single vector, it would land somewhere in the middle of all of them, close to none. So Barista has an LLM split the prompt into separate interests, embeds each one, and looks for posts close to any of them. A state: The data to judge, as JSON Questions: Each with a type that defines the shape of the answer Choice: Pick one option from a list we provide Score: Pick a level on a scale we describe (2 to 10 ordered levels) Noul: A yes/no question, answered as a probability Domain ( choice ): What is the primary domain of this post? Depth ( score ): How technically deep is this post? Quality ( score ): How well-written and substantive is this post? Paywall teaser ( noul ): Is this a paywall teaser? Spam ( noul ): Is this spam? Poor fit: largely unrelated to the user’s stated interest Weak fit: tangentially related but not a strong match Good fit: clearly matches the user’s stated interest Excellent fit: a standout match, exactly what the user is looking for Match (embeddings): from thousands of posts to a short list. Cheap, fast, approximate Rank (Jev): from that short list to the few posts in your email. Slower, costs money per call, precise Embeddings answer “what is this roughly about?” Jev answers “is this actually good for you ?” About 23,000 lines of Go, and 31,000 more lines of tests (yes, more test code than code). 22 alerts and nearly 50 custom metrics. An AI on-caller to triage alerts. A TLA+ spec, model-checked, to make sure nobody gets two emails a day. A randomized simulation that replays days of pipeline life on a fake clock. A chaos test that throws 1,000 simultaneous users at a database the size of a Raspberry Pi.

0 views

When Every Distributed Database is 'Highly Available'

An irritating thing about database vendors is that they all claim their offering is "highly available". If pressed they'll say they're talking about their SLA , and while this is not technically lying, it is very misleading, because people who know some distributed systems lore may have a much different conception of what "availability" is; namely this from the CAP theorem : The CAP theorem has been critiqued - which we'll get to - but it is massively influential. Jepsen of database report fame uses the term similarly, furnishing us with three categories of availability: In the Jepsen terminology most databases today are unavailable. A good rule of thumb is anything with a single writing node falls under this - no matter what their marketing material says. I feel availability has been diluted too far to serve in the technical lingua franca of people building systems. Database vendors have convinced large numbers of us that there isn't even a availability/consistency trade off to be made - that they in their engineering might have miraculously achieved both. It's at times like this we need an academic. Not just a specialist, but a generalist, one who is able to take a broad subject area, analyse it intensely, and understands what he reads so totally he is able to explain it to a general audience. Availablity is dead, is anybody here a doctor??? In his excellent paper A Critique of the CAP Theorem , Martin Kleppmann goes into some detail, noting both the metric that is empirically observed definition the vendors use, and the more academic one used in the literature. It's well worth reading in full, but I want to focus on his "delay sensitivity framework": reproduced here (where d is network delay): In typical Kleppmannian fashion he has managed to reduce complex phenomena from a great number of real world systems into a simple table. But I think to serve as a piece of lingo, "delay sensitive" is not quite catchy to use in real speech. And so I humbly propose consistency/latency . It works because it's a single term; that DB is high cosnsitency/latency , that one is low consistency/latency . Consistency/Latency are an inseparabable package; you are either high or low, no "strong consistency AND highly available" vendor shennanigans. I am of course simplifying a great deal of complex research, but the general rule is that as consistency rises, latency increases with it; all else being equal it's always going to be faster & more robust to directly write to your local node than wait for a consensus protocol to finish. While I desperately hope this becomes popular enough that we can call it conlat for short, I have already started using this classification when talking about systems at a high level, and will continue do so. I hope it may also serve others well.

0 views
Corrode 2 weeks ago

Thinking in Traits

Rust favors composition over inheritance. I’m sure you’ve heard that before, but rarely does anyone take the time to explain what it means in practice. Also, why is this model the right choice for Rust? Let’s take a step back and look at an example: have you ever asked yourself why works the way it does? How does know to produce a here? To answer that, let’s first look at the signature of : Note how it doesn’t mention at all. In fact, it doesn’t “know” about any collection type or any other type, for that matter. The thing it does know is that whatever type you want must be capable of constructing itself from an iterator. And happens to be a type that does. Further note that we didn’t specify the element type of the vector. The compiler is clever enough to infer that from the context! The mechanism is the same for any other supported type, like hash maps, strings, or any custom collection type of your choosing as long as it implements for the iterator’s item type. And what “collecting” means is also defined by the type itself. A , for example, has the ability to collect characters: And a can collect key-value pairs: It’s only fair to mention that interfaces can also express shared contracts. Here, two independently defined implementations connect through a shared item type. This is “composition through contracts”: Here, a producer yields values of some type through the trait. On the other side, a collection implements to describe how it can build itself from those values. The shared item type connects the two contracts, and is the bridge between them. It requires only that the destination can be constructed from the items the iterator yields. In our first example, the annotation selects the destination type. Because implements , the compiler knows how to connect that destination to our iterator. is the glue that passes the iterator to that implementation, which creates and fills the vector. Note how neither side needs to know the concrete type on the other side. The iterator doesn’t need to know how a vector stores its elements. And the vector doesn’t need to know where the items came from, only how to iterate over them. That means we can extend either side independently. A new iterator can feed existing collections, and a new collection implementing can accept existing iterators yielding . We don’t need a separate conversion for every producer–collection pair. All we need is one implementation, and is the glue that brings it all together. In simple Rust pseudocode, we can expand the calls step by step: The value of an abstraction is the code that no longer needs to exist between its users. Class inheritance models “is-a” relationships. In Java, for example, an is a subclass of . An encrypted socket is still a socket, after all. But does every socket operation make sense for it? lets a TCP connection stop sending while continuing to receive, a feature called “half-closing.” Code using a socket might therefore do this: On Android API levels 21 through 23, the platform’s implementations rejected this operation with . This caused a real crash in OkHttp 5.2.0 . Modern OpenJDK supports TLS-aware shutdown , so this is a historical mismatch, not a universal limitation of TLS. Still, the type exposed an operation without telling callers whether that implementation supported it. With composition, a TLS connection can hold a socket internally without exposing every operation on it. It can provide reading and writing, with a separate capability for half-closing where supported. We can reuse the transport without inheriting its entire interface. Simply replacing inheritance with interfaces—or traits—doesn’t fix a poorly chosen contract. What’s important is that the contract matches the capabilities of its implementations . Rust makes trait-based composition central to code reuse. In Rust, we ask what a type can do , not what it is . In other words, traits describe capabilities, not taxonomies. Here are simplified versions of two central I/O traits from the standard library: Note how these are two independent traits. A type can implement , or , or both, or neither. You’re declaring which operations a type supports, without inheriting a bunch of unrelated methods. The capabilities are orthogonal. For example: The trait implementation belongs to the type , not to a concrete value. Take , for example. It implements both and , but a file opened in read-only mode will still fail at runtime if you try to write to it. Even a file opened for writing can fail when the disk fills up. The trait implementation is a promise that the type supports those operations, but what it can’t do is guarantee that every operation will succeed at runtime. If you want to distinguish read-only and writable handles at compile time, you could define a and a and only implement the appropriate traits for each. That rules out unsupported operations in your API, but it still doesn’t make I/O infallible. Rust can express that a container has a capability only when its contents do. For example, implements when implements . Thanks to this trick, we don’t end up with two different types, one cloneable and one not. Here’s the same pattern for a small wrapper you could define yourself: A is cloneable because is cloneable. A is not, since does not implement . If you were to call on that batch, the code wouldn’t compile. You can store non-cloneable items in a batch; you just can’t clone that batch. For this wrapper, you can use to generate the conditional implementation automatically. Note that the bound belongs on the implementation , not on itself. Making your type cloneable requires , but apart from that, is still a perfectly valid type for non-cloneable elements. The compiler works out which operations are available from the capabilities of the component types . A conditional implementation can also apply to every type that satisfies a trait bound as opposed to one particular wrapper. This is called a blanket implementation . For example, the standard library implements for every type that implements : All you have to do to get a method is implement for your type. The compiler automatically generates the implementation for you. The rule applies even to types written long after the standard library itself. This is an elegant way to express a reusable implication between capabilities: “If a type can be displayed, it can be turned into a string.” The same idea appears in conversions. You might know that implementing automatically provides through a blanket implementation. That’s why you normally implement rather than writing the corresponding implementation yourself. Conditional implementations also let us add behavior by wrapping one value in another. This is a different type of composition: “composition of values.” A wrapper holds another value and builds on its capabilities. Take our trait from earlier: So a parser accepting doesn’t need separate support for files, buffered files, and length-limited buffered files. It just reads bytes! We can add buffering and a byte limit without teaching the parser about either. The parser doesn’t need to understand how its input was assembled. This works because each wrapper preserves the contract that the next piece needs. A implements when does, and so does . The result of one composition becomes a building block for the next. You can see the same idea in iterator chains. Each type implements , so you can chain them. Writing your own iterator connects your type to this vast ecosystem of adapters. All you need is to provide the associated type and the method . , , , and already have default implementations, available when their additional bounds are satisfied. This is how you reuse code without a base class. Default methods provide behavior within a trait you implement; blanket implementations can make another trait apply automatically. But adapters don’t have to be limited to a single, rigid contract either. They can provide rich, additional capabilities, too. For example, implements when its input iterator does, and it does so with an appropriate trait bound on the mapping function: So because the adapter has a conditional implementation for , it preserves the ability to iterate backward through the input. We’re not limited to basic iteration. And since we know the concrete iterator types, the compiler can optimize and inline the entire chain of adapters into a single loop. Optimized iterator code can perform comparably to a hand-written loop . So fully embracing iterator patterns has no runtime cost. Hold on, Rust has another way to express “different kinds of things that are related”: enums! These are useful in situations where you know the full list of possibilities in advance. Enums are great if you almost always want to handle all of the variants in one place. Traits are the better model if different types implement the same behavior and you don’t know all of the types right now. In other words, enums are a closed set of variants while traits are an open set of implementations. You can’t add new variants to an enum without changing the enum definition. But traits enable the open/closed principle: you can add new implementations without modifying existing code. This allows other crates to extend your library without needing to modify your code. Imagine your library defines the and types, and you want to provide a way for users to fetch records from different sources. In your library, you implement for a and a . But now, users can implement it for their own or a . Heck, you don’t even need to know these types exist. And yet, your contract still holds: any type that implements can be used to fetch records. The reverse is also true: an external contributor can define an extension trait and implement it for your type without you knowing about it. You can even do that with types from the standard library: As long as the trait is in scope, you can call the method on a : No need to modify or derive a subclass. This implementation is allowed because we define in our crate. Rust’s coherence rules restrict implementations involving foreign traits and types. For example, we couldn’t implement the standard library’s trait directly for , since neither the trait nor the type is ours. This is composition at the level of behavior : we combine an existing type with an independently defined capability. The type and the trait don’t need to know about each other. The same type can implement other, unrelated traits, and each function can ask for just the capabilities it needs by means of trait bounds: This open-set/closed-set principle is a good way to think about when to use enums and when to use traits. But to be fair, the lines can blur a bit. An enum can also implement traits, and a library can restrict who implements a trait through a technique called a “sealed trait.” In application code, exhaustive enum checking can make refactoring easier because the compiler will tell you which statements need to be updated when you add a new variant. Introduce a trait instead when you have a good reason to share a contract across types . The more unrelated responsibilities a trait combines, the harder it becomes to implement and reuse. Every implementer has to account for operations it may not need. Consider this application context: Ask yourself: what concept does this trait capture? What contract does it enforce? It combines reading records, writing records, and running the application. Perhaps your application really needs one type to provide it all, but a function that copies records shouldn’t require its inputs to run an application. Let’s split the capabilities: Now a read-only source can implement , a write-only destination can implement , and the execution runtime is left out. Your functions don’t need to know about the runtime either, and you can compose the exact capabilities you need: Each of your types can implement either trait. Or both. This also explains how independent crates work with your types. Serde defines and ; your types implement them, often through derive macros. Serde’s serializers don’t need to know about your application’s structs in advance. They just use the shared contract: a type that implements can be serialized. Code becomes more composable as a consequence. If Serde decided to couple serialization and deserialization into a single trait, some use cases would be impossible to express. All of that is great for testing, too. We can test with a fake implementation and a fake implementation, without creating a runtime. The goal isn’t to make every trait contain exactly one method. has many methods, but they are all strictly related to the task of iterating over a sequence of values, and all but one ( ) have a default implementation. It’s fine to keep methods together when they describe the same contract, but if you’re unsure if callers need the independent capabilities, split your traits. Below are a couple of concrete tips around trait design. When you approach a problem, ask what your code needs a type to be able to do. Often, an existing trait already expresses that. Check the standard library and popular crates first. And sometimes a concrete type or an enum is enough. Write the code concretely first. If you find yourself copying similar implementations across different types, look for a shared contract. By then, you’ll have concrete examples to test your abstraction against. And when you do need a new trait, give it a contract you can explain in a single sentence. Abstraction has a cost for readers. They may need to follow bounds and implementations across several files to understand a call. Sometimes that indirection hides details they shouldn’t need to care about. Sometimes it hides an important detail they should. Trait-based abstractions in Rust often incur zero additional runtime overhead, but there is a compilation cost as well. The costs depend on how you use the trait. Generic code is usually monomorphized: the compiler generates code for the concrete types that use it. That permits static dispatch and inlining, but many instantiations can still increase compile time and binary size. For dyn-compatible traits , dynamic dispatch through lets the same caller operate on different implementations, but introduces indirection and can limit inlining. Not every trait supports this: , for example, is not dyn-compatible. Keep these trade-offs in mind when you introduce a trait. There is no free lunch. Let’s come back to our once more. So far, we’ve used the destination type to choose a collection. But it can also determine control flow. For example, we can decide to stop iterating on the first error or keep going and collect every result, including errors. I first learned about this from Karol Kuczmarski’s Iteration patterns for Result & Option , still one of my favorite Rust posts. Here it is in action: Note that in both cases, the iterator expressions are identical . The only thing that changes is the destination type: In the second case, is never parsed. If every parse succeeds, the second version returns containing the vector of values. This behavior comes from the standard library’s implementation for . Here’s a stub of that implementation: What this says is: An iterator of values can be collected into a , as long as can collect values of type . The bound means that could be a or any other type that can collect those values. itself doesn’t need to know any of this: it just calls the destination type’s implementation. See how all of those pieces fit together? That’s the real payoff when you think in traits. A single implementation can connect a type to an entire ecosystem of algorithms, adapters, and collections. A few carefully crafted capabilities can combine in ways their authors never imagined. That makes the whole greater than the sum of its parts. And that’s just great API design. A byte slice ( ) implements but not . The returned by implements but not . A implements both. A implements . Wrapping it in a adds buffering, and the result still implements . Calling on that reader limits how many bytes it yields, and the result still implements . produces a iterator that applies a function to each item of the underlying iterator . produces a iterator that yields only the items of that satisfy the predicate . produces a iterator that yields at most the first items of . When you approach a problem, ask what your code needs a type to be able to do. Often, an existing trait already expresses that. Check the standard library and popular crates first. And sometimes a concrete type or an enum is enough. Write the code concretely first. If you find yourself copying similar implementations across different types, look for a shared contract. By then, you’ll have concrete examples to test your abstraction against. And when you do need a new trait, give it a contract you can explain in a single sentence. Abstraction has a cost for readers. They may need to follow bounds and implementations across several files to understand a call. Sometimes that indirection hides details they shouldn’t need to care about. Sometimes it hides an important detail they should. Trait-based abstractions in Rust often incur zero additional runtime overhead, but there is a compilation cost as well. The costs depend on how you use the trait. Generic code is usually monomorphized: the compiler generates code for the concrete types that use it. That permits static dispatch and inlining, but many instantiations can still increase compile time and binary size. For dyn-compatible traits , dynamic dispatch through lets the same caller operate on different implementations, but introduces indirection and can limit inlining. Not every trait supports this: , for example, is not dyn-compatible. collects every parse result. returns the first error and stops advancing the iterator immediately.

0 views
Farid Zakaria 2 weeks ago

A clock made of branches

What is time inside a machine you want to replay? 🧘 When building Rewind , a deterministic VM, you come face-to-face with the idea of how to represent time very quickly. You need a way to measure time inside the guest so that on subsequent replays, the guest sees the same time and makes the same decisions. Time is the ultimate variable. You can’t simply record the wall-clock time of the host because time spent between two interception points depends on things outside the guest, like host load, CPU frequency, caches and other processes. Therefore the same guest work can take a different amount of time on the host. In dafuq is a deterministic VM? I explained how the clock inside Rewind VM moves 5 microseconds per step. More specifically, that clock, exit time , moves only when the guest exits such as from a . It treats everything the program does between two exits as instant . Therefore a program that is CPU bound such as doing nothing but math for a full second between two system calls, sees only 5µs go by. 🤦🏻‍♂️ Rewind has a second clock mode as well, counter time , that tries to account for the work. The clock advances one nanosecond for every conditional branch the guest retired. 1 Aside: New to Rewind? Start with a flaky build you only catch once and dafuq is a deterministic VM? Still confused about what I mean by “free” and “branches”? Let’s look at a simple example to distinguish between the two clocks. The counter time tries to account for the work whereas the exit time only advanced the clock on exits. 2 Why branches, though? We already understand that we cannot rely on the wall-clock time of the host. We need something to measure that is the same for every run of the same program so that we can equate it to time spent. What is the same on every run? The guest’s instruction stream! The CPU is a deterministic machine: the same input, the same registers, the same memory, and the same instructions produce the same next state. We can measure time by measuring progress through the instruction stream. 💡 Turns out that CPU manufacturers even ship a hardware counter for exactly that. Is it reliable? Let’s see. 🧐 Let’s use this simple program: count down from a billion. The assembly equivalent contains a , a billion + (conditional branch) pairs, then three instructions to exit for a total of 2,000,000,004 instructions. Let’s run it on the CPU twice and count the instructions and conditional branches with : The same program and input gives the same conditional branch count, but the instruction count is off by a thousand or so. Why? Although this loop is CPU bound and only decrements a register, it is still not isolated from the effects of the outside world. Timers tick, network packets arrive, other cores send inter-processor interrupts (IPIs). The program can’t see any of that, but the instruction counter we are probing can. I pinned the loop to a single CPU 5 and counted how many interrupts that CPU took during each run, from . The dashed line is one extra count per interrupt , and the instruction counter is almost perfectly on it. 3 The conditional branch counter on the other hand, stays at zero no matter how many interrupts land. Interrupts from the outside-world are not the only thing that can skew the instruction count. The program can also page fault, which is an interrupt too. The instruction counter sees the kernel’s detour to handle the fault, but the program does not. Tip Out of the box, AMD Zen also overcounts conditional branches, a few in tens of millions, from a speculation optimization known as SpecLockMap. The fix is to set a particular bit in the PMU MSR, which Rewind does automatically as does rr#2034 . In order to rewind history, we need a measurement of time that is reliable and deterministic. Our traditional wall-clock time is unreliable due to the effects of the outside world but we do have a reliable measurement of progress through the instruction stream: the conditional branch counter. Using the conditional branch counter as a proxy for time turns out to be a relatively decent approximation. Why do we care about having a “realistic” representation of time? Plenty of programs read the clock and make decisions with it, so the guest’s clock has to be at least somewhat realistic. Under exit time, computing is “free”. A test that checks some work “finishes within 1 s” always passes. If the bug you’re chasing is a timeout, exit time will never reproduce it. 🙃 Races get skewed too with an unrealistic clock. With exit time, a whole burst of work lands in the same instant, which crowds the threads together, so a race can fire far more often in the VM than it ever would on real hardware. Some say time is an illusion. I say it’s a counter. This is the same approach popularized by the rr debugger. The rr paper calls it deterministic time .  ↩ The 5µs was my guess at a reasonable cost of a system call and context switch on current hardware. The 1ns is roughly what a conditional branch costs on a current core.  ↩ The fit is 0.94 rather than 1 because also catches the interrupts that land while and start up and tear down, before and after the loop runs.  ↩ exit time +5 µs +0 +5 µs +0, free! +5 µs +0 +5 µs 20 µs counter time +5 µs +2 µs +5 µs +1 s +5 µs +3 µs +5 µs 1.000025 s exit time: only exits move the clock. Work between two exits is instant. counter time: exits, plus 1 ns for every conditional branch of work. The counter time tries to account for the work whereas the exit time only advanced the clock on exits. 2 Why branches, though? What is time in a replayed machine? We already understand that we cannot rely on the wall-clock time of the host. We need something to measure that is the same for every run of the same program so that we can equate it to time spent. What is the same on every run? The guest’s instruction stream! The CPU is a deterministic machine: the same input, the same registers, the same memory, and the same instructions produce the same next state. We can measure time by measuring progress through the instruction stream. 💡 Turns out that CPU manufacturers even ship a hardware counter for exactly that. Is it reliable? Let’s see. 🧐 Let’s use this simple program: count down from a billion. The assembly equivalent contains a , a billion + (conditional branch) pairs, then three instructions to exit for a total of 2,000,000,004 instructions. Let’s run it on the CPU twice and count the instructions and conditional branches with : The same program and input gives the same conditional branch count, but the instruction count is off by a thousand or so. Why? Although this loop is CPU bound and only decrements a register, it is still not isolated from the effects of the outside world. Timers tick, network packets arrive, other cores send inter-processor interrupts (IPIs). The program can’t see any of that, but the instruction counter we are probing can. I pinned the loop to a single CPU 5 and counted how many interrupts that CPU took during each run, from . The dashed line is one extra count per interrupt , and the instruction counter is almost perfectly on it. 3 The conditional branch counter on the other hand, stays at zero no matter how many interrupts land. Interrupts from the outside-world are not the only thing that can skew the instruction count. The program can also page fault, which is an interrupt too. The instruction counter sees the kernel’s detour to handle the fault, but the program does not. Tip Out of the box, AMD Zen also overcounts conditional branches, a few in tens of millions, from a speculation optimization known as SpecLockMap. The fix is to set a particular bit in the PMU MSR, which Rewind does automatically as does rr#2034 . So, what time is it? In order to rewind history, we need a measurement of time that is reliable and deterministic. Our traditional wall-clock time is unreliable due to the effects of the outside world but we do have a reliable measurement of progress through the instruction stream: the conditional branch counter. Using the conditional branch counter as a proxy for time turns out to be a relatively decent approximation. Clock Time inside the VM Time on the host Exit time 2.1 s 15.7 s Counter time 11.7 s 14.2 s Why do we care about having a “realistic” representation of time? Plenty of programs read the clock and make decisions with it, so the guest’s clock has to be at least somewhat realistic. Under exit time, computing is “free”. A test that checks some work “finishes within 1 s” always passes. If the bug you’re chasing is a timeout, exit time will never reproduce it. 🙃 Races get skewed too with an unrealistic clock. With exit time, a whole burst of work lands in the same instant, which crowds the threads together, so a race can fire far more often in the VM than it ever would on real hardware. Some say time is an illusion. I say it’s a counter. This is the same approach popularized by the rr debugger. The rr paper calls it deterministic time .  ↩ The 5µs was my guess at a reasonable cost of a system call and context switch on current hardware. The 1ns is roughly what a conditional branch costs on a current core.  ↩ The fit is 0.94 rather than 1 because also catches the interrupts that land while and start up and tear down, before and after the loop runs.  ↩

0 views
Nelson Figueroa 2 weeks ago

Enums Can Be Enforced at the Database Level in PostgreSQL

PostgreSQL databases support having enumerated type (enum) columns so that the column only accepts one of a predefined set of values. I’ve worked with ORMs like Active Record from Ruby on Rails . Using Active Record, I could work with database columns that only allowed a certain set of values. I always thought that was only possible due to the ORM layer abstracting away these things, but that’s not the case. Enums can be enforced at the database level (at least with PostgreSQL). I’ll demonstrate on a PostgreSQL container with a simple table. I’ll be using Podman. You can also use Docker to follow along, just replace with in the commands. Make sure Podman/Docker is running, then run the following to get a running PostgreSQL container locally: Then exec into the running container: Now we can start setting up the table to try out enums. First, we’ll create the enum type itself. It’s going to be a type just like or are types in a database. I’m thinking of CI/CD pipelines to use as an example, so the enum will be called and it’ll only accept the values , , , and . Run this SQL query in the container: PostgreSQL should return: Now let’s create a simple table that makes use of the enum. The table will be called and it’ll have two columns: of type , and which uses our enum type . Run this in the container: PostgreSQL should return: Now let’s try inserting a row. This SQL query inserts a row where is and is one of the four predefined enum values ( ). PostgreSQL replies: We can check for the newly created row: You should see: Now let’s try inserting a row with an enum value that is not a part of the values we defined. We’ll try inserting for the column. We should get an error. PostgreSQL should say: The value isn’t one of , so PostgreSQL gives us an error. PostgreSQL itself is enforcing enums! No ORMs here. Note that the values in the enum are case sensitive. So inserting instead of will fail: PostgreSQL returns the error: Another caveat is that inserting as the value for is still allowed unless the column is also created with . Let’s say we actually want to be a part of the enum. We can modify the enum like so: PostgreSQL responds with: Now that is a valid value, we can try inserting again and we won’t get an error: PostgreSQL responds with: We should have two rows total now. We can double check: You should see: We successfully added a value to the enum and used it in a new row. One final note: there isn’t a clean way to remove a value from an enum. You can add values, but you would need to rebuild the enum if you want to remove any values. Plan ahead! Now that the demo is over, exit the PostgreSQL prompt by running: Then clean up the container and, optionally, the image: We created an enum type with predefined values, tried inserting both valid and invalid values, and it was all enforced at the database level with no abstractions from an ORM!

0 views
matklad 2 weeks ago

Avoid Public Functions Calling Other Public Functions

A small-scale rule of thumb. This article will land much better with a concrete example, but I am drawing a blank here, so you gotta just blindly trust my say so! When implementing a software module, it’s often a case that you are writing a public function , and at least part of what does is already handled by another public function . The DRY instinct encourages you to call from within . This usually creates problems down the line. Instead, create a new private function and refactor both and to call that shared helper: Rationale: the goal of a public API is to provide an interface that works best at the call site. If parts of public API are re-used to implement the rest of the API, then there’s a tension between making the interface convenient for the outside user and making it convenient to use from within abstraction itself. Namely, functions tend to grow optional parameters that should never be set by the user. Crucially, the parameter growth and interface degradation can happen after the original code sharing. By proactively making the shared implementation private, the tension is defused. You still might need to tinker with signature until it does everything it needs to do, but, because the helper is private, this is a cheap, local change. A notable exception to this rule of thumb are “shortcut” APIs, where a public function is defined as a commonly used chain of calls to other public functions. There, the rule is the opposite — no private calls are allowed, to make sure that it is a genuine shortcut, and not a midlayer mistake. P.S. While researching if anyone wrote a better blog post already, I stumbled upon a fun stack overflow question, asking, paraphrasing: I’ve heard that it is bad when a public function calls another public function. Is this really so? The most upvoted answer explains that it is indeed bad, because this makes mocking to test a single method in isolation more complicated. Which is, imo, a natural, but horrible consequence of misguided approach to testing. You shouldn’t be mocking your methods, you should mock your IO. And, similarly, you shouldn’t test methods, but rather software functionality (unless you are building a public library with a stable API, which is a fun and important, but very narrow fraction of software development). The accepted answer says that this recommendation makes no sense if it is not backed by an industry wide or an organizational standard. Which somehow manages to make even less sense — you shouldn’t follow the guideline rules because they are written in sanctified ink! Rather, you should apply each particular rule because of the underlying reasons that motivate the rule. Guidelines and best practices articles can concentrate lots of good reasoning in a single place, but they don’t absolve you from thinking!

0 views
Martin Alderson 2 weeks ago

Making agents fast - what I've learnt over the last 12 months

I've spent a lot of my career optimising websites and apps to run faster, and it's been interesting to apply some of those principles to agentic workflows. I'll run over some of my key learnings - there's many more I want to get written down at some point, but for brevity I think this is my rough mental model of tackling this. The obvious thing to start with is inference speed. This has two key components, which will be familiar if you have done any backend API optimisation. The first is TTFT (time to first token). This is analogous to TTFB (time to first byte) in web servers, namely how quickly does the first token come after you've done a request. This includes prefill (input token processing), so this scales with how many tokens the agent is sending to the inference provider too - so you should expect to see (potentially significant) variance on this number, much like you'd expect TTFB to be higher on an endpoint that e.g. has to do more database calls to prepare the response. A lower TTFT is better. Prompt caching is, of course, absolutely vital to this. Cached tokens are much faster (and cheaper!) to serve. Most agent harnesses handle this well these days - it's been a while since I've ever seen issues with this. Obviously worth keeping an eye on, but it matters less than I predicted in real world experience. The second is tok/s (tokens per second), which measures how quickly tokens come back once the response starts. This is closer to bandwidth on application servers, where a higher value is better. How relatively important each are depends on what kind of responses you're expecting back from the LLM provider. For example, if you are sending back and forth lots of short responses between turns in your agentic workflow, TTFT is likely to comparatively be of greater importance than tok/s. Equally, if you are having the LLM output longer responses (say, code or documents), then TTFT is likely to be less important than tok/s. Illustrative numbers. TTFT is network, queueing and prefill - the wait before anything comes back. Tok/s is how fast it streams once it starts. Knowing which number you need faster is important when comparing models and inference providers. Smaller models are generally faster than big ones. But between providers of the same model [1] , there is an enormous delta in speed. OpenRouter does provide public data on inference providers, but keep in mind this is an aggregate that may only roughly match your real world use. The main issue that tends to crop up is that providers also tend to vary in speed a lot depending on the time of day and how much load they are under. Big leaps in TTFT (for similar length prompts) can indicate queuing on the provider side, but can also mean your requests are being allocated to slower hardware or more users competing for prefill compute. Equally, slowdowns in tok/s can mean slower underlying hardware or higher batch sizes at the provider. Either way, there is a serious "noisy neighbour" [2] factor on many inference providers. Of course, many providers offer different tiers of service. For example, OpenAI offers a 'flex' tier alongside their standard and 'fast' tiers. These allow you to trade speed for cost. But don't overlook the impact of thinking budgets. A "fast" tier model with thinking set to maximum or xhigh will be vastly slower than a "slow" tier model with low or medium thinking. I'm guilty of constantly overlooking thinking budgets when looking at this stuff, but it makes an enormous difference. It's easy to be drawn to the quantitative tok/s and TTFT values when in reality reducing thinking can completely dwarf it - if suitable for your task. While having fast(er) inference never hurts, it's worth noting that it's often not the biggest part of the speeding up agents, and can be expensive to speed up (paying for faster tiers), or painful to move inference providers (if you have committed spend or contractual requirements). Rough numbers again, but halving inference time only takes 20% off the task when provisioning, tools and suspend/resume stay the same. It's good to start looking at your tool calls in more detail. This is much more classic performance optimisation work. But I've noticed things being slow that are not usually slow. A classic example is an agent running over large amounts of files, which causes hundreds of thousands of new process invocations. This can be painfully slow, especially on sandboxed environments. So while classic software performance engineering applies as per normal to agent tool calls, you need to investigate tool call traces to see what the agent does. It will often chain a bunch of bash commands together to achieve a result and it can be not obvious to see which part is causing slowness. is helpful here, but not ideal to run all the time as it itself has a performance overhead. Tool output size matters too. While most agent harnesses are pretty strict at stopping -style commands from blowing up your context window, as mentioned before uncached input tokens directly impact TTFT. SQL-style data sources have a big advantage if you can give your agent access to these - as it can request exactly what it needs without risk of a broad returning thousands of tokens of unrequired data. Equally, given many agents start a new shell on every command things in your that are not usually an issue can become a real issue. Be careful about what a shell needs to launch - especially if you have nvm or similar in that. Before you know it you can be spending dramatically more time starting the shell than running the command. Building on from the obvious "make this command faster", I think the next step is to think hard about what tooling your agent needs, but is having to "work around". For example, if you have it doing a lot of over markdown files over and over, it is potentially better for that data to be in a database it can call with full text search. This is where things differ a little in my mental model of software optimisation. Usually you look at a request, look at what it's doing, and try and make each part faster, and rinse and repeat. With agentic workflows, you can often just observe what the agent does, and deduce what would work better. So purely looking at tool call traces can be misleading. I've found that open weights models have a massive advantage here as you can read their thinking traces. While CoT traces are well used by the labs trying to work on safety and alignment, it turns out they are great for coming up with ideas to optimise the tools you give the agent. The way I've worked with this is getting a list of slow calls, and looking at the thinking blocks just before this. You'll usually get some blindingly obvious "hmm, could do x, but no y" style thoughts. And you can just give the agent what it wants, and see how things work out. The other thing that can make a big difference is treating loops with as a red flag. This is an indication that the agent wants to be notified of something but is instead having to poll for it. Often agents will poll for something that is quick but they tend to set a 10 or 20s minimum wait on the for loop. This can be solved with prompting sometimes, but often it can be an indication that (usually external) services need a async way to fire back task completion. Finally, parallelisation is a big help in cutting down speed of tool execution. Adding a simple "try and parallelise tool calls in $TASK" can work wonders, but especially with weaker models risks the agent making mistakes and undoing any efficiency gain. As such, providing tools (CLI or MCP) that do the parallel steps for the agent can be worthwhile. In my career, primarily driven by cloud computing platforms, I've often found the easiest quick fix is to just use faster hardware. And by faster hardware I do not mean a bigger AWS instance - dig into the underlying hardware your agents are running on. That means looking at the exact CPU core type you are using (the Zen 4c/5c cores can be much slower than the full sized ones), clock frequency and file IO speeds. This depends heavily on the tasks you're doing with your agents, but if they need to write a lot of custom code or doing a lot of data analysis, making sure the underlying hardware is fast can help a lot. For example, if your agent needs to do quite IO-heavy tasks, you may find a lot of your slowness is coming from networked disks. Having faster (local) NVMe disks may offer many, many orders of magnitude faster IO performance. This is often worse in many sandboxes. With things like copy on write and other snapshotting techniques, there can be a lot of overhead on file IO. Slow underlying IO just makes everything worse. I often see real speed issues with suspend and resume. Not every agentic workflow uses it, but if you (for example) allow agents to pause for a human in the loop approval, you need to be careful with optimising suspend and resume. MicroVMs can often resume on paper extremely quickly, but actually have pages streamed in on first access. So you need to measure not just what the MicroVM says but how quickly new inference requests are starting after resume. Being careful with memory management is the crucial thing here. While you don't want to starve your VMs of RAM and thus cause swap or OOMs, it's worth investigating what is using RAM during a suspend. If you have for example headless browser sessions active, it's almost certainly worth killing them before suspending, as is any running server processes the agent may have built. As always, the key thing is to measure and track RAM usage and break it down over time if you are using a lot of suspend/resume cycles. Finally, check the network. It's very common in my experience to have broken IPv6 in sandbox environments, and you end up with network timeouts while it does a AAAA lookup on DNS, which adds a small overhead to every request. Basic hygiene stuff like this adds up over the course of an agentic session. I think the key things I'd check on any agentic optimisation project are: As always, this space is also evolving fast. Keeping up to date with the field has always been my guiding north star in making sure you can keep stuff fast. I'd love to hear from you if you're working on making agents faster. I'm especially interested if you think I'm missing obvious factors here! Be aware that even the same model may have different quantisation (compression) depending on the provider. You need to compare apples to apples - if one provider serves FP8 and another INT4 (say), it will be faster but at the cost of quality. ↩︎ Noisy neighbour refers to shared compute getting slower when other users of the same hardware are pulling more resources. Typically you'd see this on VM providers with shared CPU resource - it may be fast a lot of the time, but when other customers are running high-load tasks, the hypervisor starts throttling each user. Unlike on VMs, where you can usually see this with 's column, it's very opaque at what load your inference provider is under. ↩︎ Inference speed is nuanced, and knowing what part of inference you rely on most for speed is important. Check thinking budgets! This is overwhelmingly the lowest hanging fruit Read traces, and if you are using open weight models read the CoT thinking traces. They often have so much valuable insight into what the agent is wanting to do Give the agent the tools it wants rather than what you think it needs Don't overlook the basic stuff. Faster hardware still matters, sandboxing and microVMs open a whole world of potential performance footguns, parallelisation helps and classic software performance optimisation is as relevant as ever. Be aware that even the same model may have different quantisation (compression) depending on the provider. You need to compare apples to apples - if one provider serves FP8 and another INT4 (say), it will be faster but at the cost of quality. ↩︎ Noisy neighbour refers to shared compute getting slower when other users of the same hardware are pulling more resources. Typically you'd see this on VM providers with shared CPU resource - it may be fast a lot of the time, but when other customers are running high-load tasks, the hypervisor starts throttling each user. Unlike on VMs, where you can usually see this with 's column, it's very opaque at what load your inference provider is under. ↩︎

0 views
Blargh 3 weeks ago

HTTP/3 load balancer connection offloading

In a previous post I described load balancing for TCP-based HTTP with connection offloading , and mentioned that HTTP/3 can do even more. By the power of AI writing an HTTP/3 version of both the load balancer (sni-router-h3) and the webserver (tarweb-h3), I have experimented enough to have more to say about how that works. To be clear: this post is 100% human-written. In this post I will use this terminology: While it is possible to use to transfer an established connection between machines (from router to backend), it requires some more infrastructure. The kernel on the chosen backend must be synced up on the connection state (sequence numbers, etc) that provides, but that’s actually just the easy part. It must also be able to send packets to the client with the original server’s IP address as source, and packets going from the client to the backend must somehow find their way to the same backend, in a network-efficient way. There are other problems too, like what to do if a client sends a with a source port equal to an existing connection. Which connection should win for the routing state machine? Take the example where the load balancer in New York wants the backend to be in Oslo, because the client is near there. For backend-to-client packets, some network hop on the way may drop the packets due to reverse-path forwarding (RPF) , because it thinks that IP address should be in New York, and therefore the packets look like spoofing. For client-to-backend packets, there’s no way to announce to the Internet the difference between initial packets that should go to the load balancer, and those that should go to the backend. The difference is just the client IP address and port. And the Internet (specifically BGP ) does not work that way. If you have a worldwide presence and private fibre network on the scale of Google or Amazon, this is physically possible. “Be everywhere” and then on every new connection you can “just” reprogram all your edge router infrastructure to route packets arbitrarily over your own world wide (physical) network, to traffic engineer however you want. But this is basically only if you have your own world wide “internet” that treats “the Internet” as an equal. Yes, for client-to-backend you could use stabilized anycast if you’re merely medium sized, but this can only solve the problem if the backend and the load balancer should take the same path. You’ll need all backend locations to also be load balancing locations, and vice versa, to have it be optimal. And it can break for longer lived connections in a dynamic world. (A full discussion about anycast TCP is out of scope for this post, but though I could have made a mistake or have been unclear here, and invite you to correct me on, if you’re thinking “well, actually you can just…” right now, you can safely assume that I know and I’ve deliberately left it out.) HTTP/3 is UDP based, and is not picky about “the 4 tuple” (the values of source and destination IP addresses and ports). Migrating a connection therefore doesn’t involve BGP peering or other network tricks. HTTP/3 can thus let the Internet be a simple packet delivering network that just takes the closest path between smart endpoints. As was always the dream. For a new connection’s TLS handshake, a client will send the SNI. A SNI router can then make a routing decision, and forward the packet to the backend. During this handshake, the router needs to remember the mapping from Connection ID (CID) to the backend it selected when it saw the SNI. After the handshake is complete, the client and the backend can open new connections with new CIDs. This is so that a passive evesdropper cannot track connections, including as they migrate if the client roams somewhere else. Since the router also never sees the plaintext, it is not aware of the new connection ID. It could fall back to remembering the client host-port pair, but clients can migrate, and that should not break connections. It can be used if the client migrates during the handshake, though. Even if it did know about the new Connection ID (which it doesn’t), or remembered the client IP-port pair (it can’t, because client address migrations), it shouldn’t need to know about this forever, e.g. across router restarts. This case is solved by QUIC-LB . Outshort, the backend will put its “backend ID” into the new Connection ID, and the router can then use that to make sure it forwards to the same backend, even without keeping any state. An entire QUIC Connection ID is at most 160 bits, so there isn’t spare room to put a whole 128 bit IPv6 address plus 16 bit port in there. The solution is to have a lookup table from backend ID to backend address:port. The Connection ID with the backend ID is then optionally encrypted, so that attackers can’t control it for whatever nefarious purpose. If we were to stop here, it could be to prevent attackers from targeting a specific backend. But handling case 3 nicely, below, forces us to publicly expose backends anyway. QUIC-LB is a draft standard, but in my case both router and backend follow the same standard, and therefore work together. For sni-router, the config looks like this: The config ID is there to allow changing the backend list over time, as a generation number. Though it’s only 3 bits, so few config generations can be active at the same time. But case 2 shouldn’t happen, because… During the TLS handshake, which always goes via the router (though the router only forwards. It doesn’t “speak” TLS), the backend may announce a “preferred address” (a separate one for IPv4 and IPv6), in other words that backend’s real IP address. The client should then stop sending packets to the router, and instead send directly to the backend. From the backend’s point of view, the client just migrated, and it too will start sending packets directly, bypassing the router. The router is now no longer part of the connection. Unfortunately it’s not mandatory that clients respect “preferred address”. And the backend can’t unilaterally send directly to the client on its own, because . So if the client doesn’t support preferred address, then we fall back to Case 2, and the router has to take the network load of the traffic. At least it doesn’t have to decrypt anything. In my brief test, Chrome does respect “preferred address”, but does not. For command line testing, ngtcp2-client has a client that works. Yeah. Outthis tcpdump (on the client) we see a connection setup seen by running: If you run this test yourself against my example setup, don’t be confused by the router and backend being on the same address, just different ports. They happen to only have different ports, but it would work equally well if they were on different machines. I have not dug into the exact packets to/from the router post-handshake. My guess is that it’s probably the client tearing down that part. But remember, the router does not speak QUIC at all. Anything the client sent to the router ends up as-is on the backend. And anything the backend replied back to the router goes untouched back to the client. In my setup the backend allows new connections created directly for it. That can easily be prevented, by having the backend blocking new connections that don’t come from the router. Clients may be able to spoof the source to appear to be the router, but then they should not get any replies, so the connection establishment will fail. client: E.g. a web browser. router: A load balancer / traffic router, that inspects SNI and forwards to matching backends. Mine’s called sni-router . backend: A webserver. Mine’s called tarweb .

0 views

Go update your PHP version now!

If you're running a blog that is built on PHP (for example, Pure Blog), you need to update your PHP installation right now. Critical vulnerabilities have been discovered in PHP, putting any PHP application at risk. So SSH into your server, run and then run to ensure you are now running one of the patched versions ( 8.5.12, 8.4.27, 8.3.36 and 8.2.35 ). Don't delay, act today!

0 views

UUIDv7 doesn't have the properties you think it does

I’m going to call it. UUIDv7 is weird. Most blog posts about UUIDv7 tout these benefits: But none of these properties are strictly held. Certain RFC compliant implementations of UUIDv7 violate these properties to extreme degrees. The only useful property UUIDv7 appears to strictly provide is uniqueness and therefore collision resistance. I’ve already discussed how UUIDv7 IDs can be guessable , so this post explores the other properties. Superficially, it seems that embedding a timestamp in the ID can remove the need to track the creation time in a separate database column, providing marginally more efficient database operations. If you need to list things ordered by creation time very often, it’s useful if the primary index gives that behavior, removing the need for another index. Unfortunately, the timestamp embedded in a UUIDv7 ID may not relate to the object creation time. The Postgres docs for helpfully warn that “the extracted timestamp is not necessarily exactly equal to the time the UUID was generated”. RFC 9562 allows implementations to alter the timestamp field, using values that aren’t strictly derived from the system clock. This relates to the tension between UUID monotonicity and timestamp accuracy. In certain scenarios, the difference between the timestamp and the current time can be arbitrarily large. Implementations MAY alter the actual timestamp. — RFC 9562 §6.1 This specification makes no requirement or guarantee about how close the clock value needs to be to the actual time. — RFC 9562 §6.1 … implementations MAY increment the timestamp ahead of the actual time … — RFC 9562 §6.2 Incrementing the timestamp ahead of the system clock is an interesting problem. If the generator is seeing so much load that a counter field is regularly overflowing then the timestamp could accelerate into the future. Using a sufficiently large counter would be wise and the RFC says the minimum size SHOULD be 12 bits. A counter overflow would require a pretty aggressive creation rate, over 4,096 IDs per millisecond per node, which is beyond the limits of many systems. This overflow becomes relevant, however, if the timestamp freezes; which I’ll discuss in a later section. One prominent implementation that increments the timestamp is the Python standard library’s UUIDv7. The increment happens only in certain circumstances, like when the counter overflows. Unfortunately, the generator can get stuck in an increment cycle if the clock ever jumps backwards and the timestamp can race ahead of the system time by an arbitrarily large amount. Here’s a simple example: Which gives: We expect the difference to be 3600 seconds (one hour) as the implementation refuses to allow the embedded timestamp to jump backwards and we expect the difference to decrease as the system clock catches up to the frozen timestamp. But when the load is above one ID per millisecond the difference will increase without bound. At lower loads it will take longer for the system clock to catch the timestamp, but we don’t see the runaway effect. The related issue shows Python developers reasoning that this is consistent with the RFC, is consistent with other implementations, and that there isn’t “much we can do” on a “flawed system”. I think these points are correct as I see this same behavior in other implementations. Nevertheless, it would be helpful if existing UUIDv7 implementations could handle system clock jumps without runaway behavior. There are many real-world examples of clocks jumping backwards, even decades out of sync in time-sensitive environments. Embedding the timestamp in the ID means that you cannot share the ID without also sharing the timestamp. It’s pretty difficult to think of an example where this really matters. One example could be a user profile page that doesn’t disclose when the account was created, but the UUIDv7 ID in the URL leaks the high-precision timestamp. This issue would typically be very low on my list of security concerns because I find much more severe problems when I do security assessments. Nevertheless, there are contexts where this matters and engineering resources would be focused on addressing it. If you’re in the latter camp, be wary of UUIDv7 leaking metadata. This section is even more pedantic, so skip ahead if you’ve had enough. Briefly: UUIDv7 IDs provide some sort of rough order, which may be suitable for your requirements. When I was reading the UUIDv7 RFC I was surprised to see it describing a method for creating IDs across different nodes that are monotonically ordered. This was proven impossible back in the 1970s , and lead to the development of vector clocks and similar technology. At a high level, the problem is that system clocks cannot be synchronized to a suitable precision. Ordering things by timestamp only works if you know precisely what time it is. Any uncertainty in the time results in uncertainty of event ordering. Succinctly: Timestamps are only time-ordered if you know what time it is and you don’t know what time it is. For this reason, similar ID formats claim to be nearly sorted. It seems odd that UUIDv7 makes a stricter claim and does not deliver on them. At the very least, the challenges of synchronizing clocks across systems make the millisecond and especially the sub-millisecond timestamps quite suspect. But even on a single node, using a single implementation, UUIDv7 IDs are not strictly monotonic. The easiest way to get out-of-order UUIDv7 IDs is to use an implementation that uses a millisecond timestamp without a counter. This approach trivially generates out-of-order IDs inside a small for loop . So no, there’s nothing in the UUIDv7 specification that would ensure the IDs are strictly monotonically increasing. Specific implementations may do better than others (with sub-millisecond timestamps, counters, well-synchronized clocks, etc), but we’ve known since the 1970s that this problem is not strictly solvable. In UUIDv7’s favor, roughly ordered IDs are still quite useful. So don’t rip UUIDv7 out of your systems just yet. Just be wary of what assumptions you have. The RFC has lots of discussion about the handling of clocks that jump backwards. Timestamps are only time-ordered if clocks tick forwards, so special care is needed. We’ve already discussed one mitigation: tracking the last generated timestamp to ensure that an earlier timestamp is never used. To do this safely you’ll need to write the last used timestamp to persistent storage, such that you can read it again after a system reboot or a process restart. I’ve looked at several UUIDv7 implementations I couldn’t find one that writes timestamps to persistent storage. So implementers seems disinterested in addressing the issue and they generate out-of-order IDs when a process restart follows a clock jumping backwards. Looking at real-world clock synchronization problems, you’ll find many examples of clocks getting set to future dates . When this happens, the backwards jump would align the timestamp to the actual time, but a last-used-timestamp guard would force timestamps to use keep using that incorrect timestamp until the system clock catches up. If the system clock takes a long time to catch up, you may start experiencing counter rollovers. My mental model for UUIDv7 is that it’s a mash-up of a bunch of different ideas which implementations are free to choose as they see fit. There’s a wide variance of properties that UUIDv7 implementations can provide, with varying degrees of certainty they can successfully provide those properties. If you’re building your own implementation you can likely build something that has the properties you need. But most of us want to reach for an off-the-shelf version, especially when standard libraries provide an implementation, so we’re generally at the mercy of someone else’s implementation decisions. Implementations can change over time, making broad changes to their behavior while still being RFC compliant. Distributed systems may have multiple implementations across their subsystems, each with distinct properties. The only thing you can really expect is strong collision avoidance and ID uniqueness. Be sure to ask these questions when picking a UUIDv7 implementation: Unfortunately, this sort of analysis is much more difficult than building an RFC compliant generator. Authors of UUIDv7 generators may not know the answers to these questions and may themselves be surprised that the RFC does handle this for them. Hello! I'm Robert Alexander, a DevSecOps consultant available for contract work . This blog features some of my work and thoughts on software, the cloud, and security. You can subscribe to my posts with your favorite RSS client and follow me on Mastodon . If you'd like to show your appreciation and help support my writing, you can do so via this link. monotonically increasing IDs a helpful timestamp of when the object was created; and unguessable IDs Is the implementation compliant with the RFC? What additional properties does this implementation guarantee? Under what limits can those guarantees be met? Are there any assumptions required for these properties to hold, such as having an accurate system clock? Under what conditions will the implementation alter the timestamp? How guessable are the generated IDs?

0 views
Sean Goedecke 4 weeks ago

What requirements don't you have?

When designing software, the requirements you don’t have are as important as the requirements you do. Identifying what you can compromise on — what can be slow, or stale, or inflexible — is usually the key to an elegant design. For instance, take preforking web servers like Unicorn . Because they lack the feature of shared mutable state between server instances, they can run each server in its own process, which provides isolation for free. Because Unicorn specifically ignores the problem of slow client handling 1 , it can queue requests directly on Unix sockets, drastically simplifying the implementation. Because S3 does not support atomic multi-key updates — you cannot update multiple blobs in a single transaction — it can store data at the blob level however it chooses. That makes it much faster, since reads and writes don’t have to cross storage partitions, and much easier to scale, since less coordination means fewer sources of truth. StatsD uses UDP by default, which means it doesn’t guarantee that every piece of data you send makes it into storage. In exchange for dropping that requirement, it incurs much less network overhead, which is a big advantage for a stats aggregation service that’s constantly shoveling data over the wire. The general design approach of fanning out data to an edge cache buys a lot of speed and scaling by dropping the requirement that data must always be up-to-date. SQLite buys operational simplicity — it can run out of a single file! — by dropping the requirement of concurrent writes. By accepting high tail latency 2 , Cursor can scale their distributed git backend more easily. Well-designed systems turn their weaknesses into strengths. Anyone who’s spent time designing real-world software (or who’s studied distributed systems ) knows that system design is a process of compromise. If you attempt to satisfy every single potential requirement — speed, concurrency, up-to-date data, a simple interface, supporting complex user behaviors — you will fail to design a working system at all. Figuring out what requirements you can relax is difficult because it combines both business and technical expertise . It is technically challenging to identify precisely the level of staleness that a particular design change will allow; it is likewise challenging from a business perspective to determine whether that level of staleness is acceptable to users. In most cases, an engineer who understands the technical side must try and explain it to a product manager, who can make a judgement on the business side. But this is a very difficult partnership to get right. Engineers and PMs have different incentives and little ability to check each other’s work, which makes it hard to build trust . Without trust, the product manager is liable to avoid giving any ground at all 3 , which leaves the design in an impossible state. This is an underappreciated reason why solo developers or startups can sometimes run rings around larger companies. Because the technical and business decisions are united in a single person, they can make design tradeoffs that would be impossible for a large company, enabling them to build systems that are far more elegant and powerful. Knowing what requirements you don’t have becomes far more important when working with coding agents. Frontier models are very capable, but they have all gone through the purifying flames of RLVR : like high-achieving schoolchildren, they are obsessed with satisfying the Grader. On top of that, they have very little business context compared to an experienced human. That often manifests as them catching correctness or consistency “bugs” that are really just hypothetical unsatisfied requirements. For instance, it’s not uncommon for an LLM to casually introduce a mutex or other concurrency mechanism to ensure that two pieces of semi-related data are kept in sync, even if not told to do so. I’ve seen LLMs add weird checks in the middle of request handling to ensure that some already-checked piece of data hasn’t changed mid-flight, even if that wouldn’t successfully prevent the feared TOCTOU bug 4 . LLMs are obsessed with edge cases like “what if the current user loses their admin status in the middle of us handling one of their admin requests?” 5 , or “what if the cache in storage partition A is updated a nanosecond before the one in storage partition B, leading some users to see different data?“. Particularly if run in a loop or told to “make no mistakes”, they will pile on cases like these until they’ve transformed your four-line change into a thousand-line monster. This is why I’m confused by some people’s claims that code review is dead . About half the time I review a large AI-generated change, I notice some unnecessary requirement that makes the diff more complex. When I dig deeper, the LLM invariably introduced this requirement on its own. When working with a cache, I will often spell out in my prompt that I don’t mind the data sometimes being stale or briefly inconsistent between cache instances. When reviewing Golang code, the first thing I do is scan for added mutexes or layers of indirection that don’t look necessary to me. If you allow requirements like these to propagate unchecked through a codebase, they will petrify the system over time. The whole thing will be such a mess of checking and re-checking and holding locks and enforcing consistency that it cannot be scaled at all. Keeping systems elegant requires a ruthless focus: on accepting stale data or occasional tail latency, on avoiding all but critical instances of coordination, and in general on figuring out what requirements you don’t have to satisfy. The problem: if an HTTP request sent by someone with slow internet trickles in one packet per second, does that have to tie up a server process for the whole time? Unicorn’s answer is ‘yes, so put nginx or HAProxy in front of me’. When a read request hits a stale storage node, that node must update itself before responding. I’ve also seen this happen in reverse, where the product manager desperately tries to convince an engineer that some level of stale data is acceptable, while the engineer digs their heels in and insists on the “perfect” system. The consequences are similarly dire. Of course, simply doing a separate check shortens the TOCTOU window instead of removing it. In every single system I’ve worked on, it would be fine to simply carry out (or fail) the admin request: if somebody was allowed to perform some operation 10ms ago, it’s likely not a disaster to let them perform it now. The problem: if an HTTP request sent by someone with slow internet trickles in one packet per second, does that have to tie up a server process for the whole time? Unicorn’s answer is ‘yes, so put nginx or HAProxy in front of me’. ↩ When a read request hits a stale storage node, that node must update itself before responding. ↩ I’ve also seen this happen in reverse, where the product manager desperately tries to convince an engineer that some level of stale data is acceptable, while the engineer digs their heels in and insists on the “perfect” system. The consequences are similarly dire. ↩ Of course, simply doing a separate check shortens the TOCTOU window instead of removing it. ↩ In every single system I’ve worked on, it would be fine to simply carry out (or fail) the admin request: if somebody was allowed to perform some operation 10ms ago, it’s likely not a disaster to let them perform it now. ↩

0 views
Unsung 1 months ago

“Traditional, but puzzling”

In the 1990s, users of some Unix-based operating systems would sometimes see a peculiar error. It happened occasionally when sending an email to a person you might have already sent email to before, and in addition to the error being confusing, the message itself was particularly bewildering. Let’s say you wanted to send an email to “MWichary.” Instead of a confirmation, you would see this: As many strange errors tend to be, this one was at an intersection of four different things. The cause of the error was something many of you will recognize – code being anal about lower- and uppercase. Behind the scenes, a piece of software called sendmail always assumed lowercase user names, which was true early on. “MWichary” was quietly changed to “mwichary” – a user that didn’t exist – and the program reported the literal outcome, instead of its chain of reasoning. The second part was a sort of a meta-error in the error handling routine. Sendmail correctly reported back “User unknown,” but then reflexively added whatever the system error value reported, for extra debugging color. These are usually helpful, reporting things like “Host is down” or “No space left of device” – I bet you’ve seen some of the very distinctive strings if you ever did anything adventurous in the terminal. In this particular context, however, the system error was pretty useless. “Not a typewriter” meant basically “this is a program being run in the background; it’s not meant to accept any user input or write anything for the user to read.” It’s not an error as much as a condition , and is true for a lot of programs quietly doing the operating system’s bidding. But… why was the message phrased this way? That’s just history. Computers were originally connected to typewriters as input/​output. Some of these typewriters were local, attached to the front panel, or console . Others were remote typewriters, or tele typewriters, often shortened to teletype or even tty. If you recognize these terms, that’s because they are still with us today! = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/traditional-but-puzzling/1.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/traditional-but-puzzling/1.1600w.avif" type="image/avif"> = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/traditional-but-puzzling/2.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/traditional-but-puzzling/2.1600w.avif" type="image/avif"> = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/traditional-but-puzzling/3.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/traditional-but-puzzling/3.1600w.avif" type="image/avif"> You can see how “This doesn’t have input/​output I can do something with” can become a terse “Not a typewriter” in an era when every character feels costly , and a typewriter is your only option for input and output. Then, the string was simply kept a few decades too long, even after typewriters were replaced by teletypes, terminals with screens, and eventually Terminal and Console apps. The fourth piece was fun with grammar: the simple choice of joining the two messages by a colon made it feel like the user was supposed to be a typewriter. The message was eventually renamed. If you encounter it today, it will say “Inappropriate ioctl for device,” which I guess is an improvement. But its code remains . It’s entirely possible it will still be named that decades from now, even after we all forget what typewriters were. (The title of the post comes from the explanation in the manual for the Solaris operating system .)

0 views
Chris Coyier 1 months ago

Archived Tweets

I finally got around to importing my whole historical Twitter archive (just my own original tweets, not replies or retweets) into this WordPress site as a proper Custom Post Type: https://chriscoyier.net/tweets I haven’t added it to the navigation or anything else on the site yet. Not sure what I want to do there. Just feels good having my own data. The Tweets show up in the Jetpack-powered search too, which I’ve found nice. I used this and hacked it up a bit to fit my needs, and so I didn’t have to leave it as a permanently installed plugin. It’s coming at a weird time, with quite a few people “going back” to Twitter. It’s actually called X now; I’m aware. It’s named after the hand gesture you do when Elon Musk asks if you’d like to come over for a dinner party: 🙅‍♂️ Casey Newton just saying, “Look, I tried, but X is where the action is,” and John Gruber being like, “Take a whiff; the Elon stench is gone.” I understand both of those things. I honestly really like both Mastodon and Bluesky, but after years and years, the fun and engagement have never reached old Twitter norms. And I miss that! But it also feels like you have to ignore a lot of bad behavior to use a platform that Elon Musk not only owns but literally bought to be his megaphone and power center. Do people not remember the horrible shit he would do on a near-daily basis? Tasteless, dangerous, and often both. I can remind you! Here’s just one straw from a haystack. Elon loves him some Trump. They are big buddies! Elon shouldered up to Trump for the power, and Trump gave it to him. Elon decided to take this power (granted to him by a scepter touch? apparently?) and created a real government organization called DOGE, which is a joke name, named after a joke cryptocurrency that is inherently corrupt. DOGE’s job was to make the government “more efficient” by eliminating funding for tons of stuff. One of the things they did was entirely get rid of the USDS, which was the organization that did incredible work, ya know, making governmental websites far more efficient. Now, our government makes racist video games on the web instead. Not kidding. That’s a fucking game on our own government’s website, where you play a white dude who walks around a page collecting brown people to deport. I find it more than a little hard to swallow.

0 views
Nick Khami 1 months ago

The STT-LLM-TTS voice stack is dead

I went to get a skin analysis done thru @layersbio and it came back with a bunch of areas for improvement that i wanted to action on which required getting some prescriptions. I started booking appointments to get those and was immediately frustrated that my agents couldn't call to do it for me. So, naturally, I tweeted asking for a product to solve this. To my immense disappointment, there wasn't anyone who had built this yet. I got a few replies from devtool style companies that had made voice AI APIs, but I really just wanted a managed solution and couldn't find one. I figured that there were enough other people similar to me who use a lot of agents but didn't like making phone calls that I decided it was actually worth building the tool myself and launched call4me . Based on the revenue, I feel like that instinct was correct! You add one MCP URL to your agent. Then you say something like "call my dentist and move my cleaning to next week, any morning works" and the agent does the rest. The important design decision is that the caller can only say what it was given . A phone call is a terrible place to discover you don't know the patient's date of birth. So before dialing, the agent has to collect everything the call will need: If something is missing, refuses with "Not calling yet" and lists exactly what to ask the user. The agent asks, retries, and only then does the phone ring. During the call the agent polls for progress. If the business asks something the caller doesn't know, the question shows up for the agent, the agent asks me, and my answer gets spoken on the call. If the business insists on talking to me, my phone rings, I press 1 to join, and I press star to hand the call back. After hangup, a recap written from the transcript lands in the agent's context. Everything runs on Cloudflare. The site, MCP server, API and webhooks are one Worker. Calls run in a separate Worker, where every live call is its own Durable Object. D1 holds accounts, calls and an append-only credits ledger. Stripe handles payments. The part I'm happiest with is how little the audio path does. Telnyx Call Control places the call and opens a two-way media stream over a WebSocket. GPT-Live accepts audio in G.711 μ-law at 8 kHz, which is exactly what a phone line already carries. So the Durable Object just relays frames in both directions, untouched. There's no speech-to-text step, no text-to-speech step, and no resampling. Every stage you skip is latency you don't pay and a failure mode you don't have. The voice model hears the phone line exactly as it is, hold music and all. One small detail that mattered: the GPT-Live session starts when Telnyx says the call was answered, not when we dial. Otherwise the model sits there listening to ringback and gets confused about whether someone is on the line. Most voice agents are cascaded: speech-to-text transcribes the other side, an LLM writes a reply, and text-to-speech reads it out. call4me isn't. There is exactly one model on the audio path, GPT-Live, and it hears audio and speaks audio directly. The text model further down this post only makes decisions. It never sits between the business and the voice. Cascades are popular because every piece is swappable and the LLM in the middle is a normal text model that's good at tools. But each hop adds latency, and turning speech into text throws away everything that isn't words: tone, hesitation, someone talking over you, the difference between hold music and silence. On a phone call those are most of the signal. Going speech-to-speech has worked out well. Interruptions mostly handle themselves. GPT-Live stops talking when it's talked over, and the only thing I had to add was flushing audio that was already queued at Telnyx, so the business doesn't hear the end of a sentence the model already abandoned. Cost isn't a blocker either: GPT-Live costs about 5¢ a minute, a small slice of the 25¢ a minute call4me charges. The real tradeoffs are the ones the rest of this post is about. A realtime model is worse at acting reliably than a text model, so it doesn't get tools. It only speaks when it hears something, so silence while it waits on me is my problem to fill. If you're weighing a switch away from a cascade, those are the two things to plan for. GPT-Live is great at conversation and bad at being trusted with side effects. So it doesn't get any tools. Instead it delegates to a "back office": a regular Responses API model that owns everything that changes the world. The session config looks like this: The voice keeps talking while the back office thinks. When the business says "can I get the account holder's zip code?" and the caller doesn't have it, the voice says something natural, and the back office calls . That question goes out over MCP to my agent, my agent asks me, and my answer gets injected straight back into the voice model to say out loud. This split is the whole product. The fast model handles the conversation and the smart model handles decisions. Most calls to a big company never reach a person without getting through a phone menu first. This was by far the hardest part to get right, and most of the code in the voice folder exists because of it. The first bug was funny. A menu says "for billing, press 2" and GPT-Live confidently says "2." out loud. A phone menu only hears the keypad, so it repeats itself, the model says "2." again, and you get a loop that runs until the menu hangs up. The voice model is supposed to delegate to the back office, which calls . Sometimes it just doesn't. No delegation event, no error, nothing runs. Same thing with "let me check on that real quick" followed by silence, or "bye!" followed by never actually hanging up. I couldn't make the model reliable, so the session watches the transcript itself. A set of patterns spots phone menus and spoken promises: If a menu finishes speaking (3 seconds of quiet) or the caller makes a promise (1.5 seconds) and no hand-off follows, the session starts the back office on its own and tells it what was missed. Getting the first key right isn't enough. Menus lead to dead ends: "no input was received", "that selection is not valid", or worst of all, "please visit our website" and a hangup. A class tracks fresh menu speech separately from the transcript, remembers every key the carrier accepted and what prompt it was answering, and watches for failure phrases. When a menu fails, the back office gets the full key history and one firm rule: never repeat a route that didn't work. Back out to the main menu, try "other questions", try for a representative. Speech-driven menus were their own problem. FPL and UPS both looped for about 8 minutes before I taught the caller the magic words: say "representative", and if that doesn't work, say "agent". Telnyx's sends keypresses as out-of-band RFC 2833 events. That works for US phone menus. On a call to Dubai Opera, the menu just kept repeating, because the UAE route was stripping those events. The fix was to stop asking the carrier to press keys and press them ourselves. For any number outside +1, the caller now plays real keypad tones into its own audio: two sine waves per key, 120 ms of tone and 80 ms of gap, encoded to μ-law and spliced into the outgoing frames. A tone inside the voice audio survives any route that carries the voice. A Durable Object can be reset when you deploy. On launch day, every call that went deaf was one of those resets. The fixes stacked up: a 20 second heartbeat that asks Telnyx to reattach the stream, resuming GPT-Live with the transcript so far so it doesn't greet the business twice, and treating "no audio 4 seconds after pickup" as a lost stream. The real fix came after a blog deploy cut off a user's demo call mid-sentence. Calls now live in their own Worker, and the deploy script for that Worker only ships when the bundle actually changed and no call is live. The first version dialed me in as a Telnyx supervisor with full speaking rights. My voicemail picked up, its greeting played onto the business's line, the voicemail hanging up looked like me handing the call back, and the system rang me again. In a loop. Now my phone rings listen-only and I have to press 1 to join. If 30 seconds pass with no keypress, it's voicemail. Once I'm on, my own keypresses get forwarded to the business too. I found that one the hard way when the Experian menu asked for my SSN and my keypad did nothing. The voice model only speaks when it hears something. So when it asked me for a one-time code and was waiting on my answer, the line went dead. A Spectrum rep sat through 41 seconds of silence. Now, every 15 seconds or so, the caller says "sorry, still checking on that, one sec" until the answer arrives. You can try it at call4.me . Calls are 25¢ per minute, and unanswered calls are free. A saved profile with the stuff businesses always ask for: legal name, date of birth, phone, address, insurance, car. Per-call requirements by category. There are 12 of them (medical, dental, restaurant, vet, auto service, internet, flight change, and so on), and each lists the fields that kind of business will ask for. Skip every audio conversion you can. Matching the carrier's codec end to end made the audio path the most boring part of the system, which is exactly what you want. Split the voice from the decisions. A realtime model with tools will press the wrong button eventually. A realtime model that delegates to a reasoning model is much easier to control. Don't trust the model to act. Verify. The most valuable code in the repo is a few regexes that notice when the voice said it would do something and didn't. Gather everything before you dial. The caller can only say what it was given.

0 views
Jason Scheirer 1 months ago

Oh, Goddammit: I'm Back on C++ in 2026

The title for my autobiography would probably be I Thought I Was a Child Prodigy But I Am Actually a Late Bloomer . Going from being the youngest guy in the room to the oldest guy in the room happens suddenly, surprisingly, and permanently. As such, the programming languages and technologies I learned long ago are esoteric knowledge but the systems they run on still exist. Everything’s moved up a level of abstraction or six and there’s a lot of low-hanging value in plain old systems programming again. So for the first time since 2014 or so I found myself writing C++ starting March 2026 and carrying over to today in late 2026, both dates in 2026. 2026. From the start, quite simply: Windows APIs. Relatively obscure ones. They come with C++ headers and opaque files and COM interfaces that fall well outside of the coverage footprint of . I’m writing RDP plugins , which with some gymnastics I could do in Rust but it would be a lot more work to do the cooler thing. It’s less friction to just say “okay” and do it the way they tell you to do it. Spend those innovation tokens on cooler shit than this. And I’m doing Citrix channels , which are straight up C++ or Go Fuck Yourself (I believe the SDK docs explicitly use this language). Also, there are old features that aren’t exposed to moderns stacks that give us easy wins that exist on users’ systems without additional upgrades or installs. The RDP client bridge binary I wrote is under 50k. It builds in 3 seconds. It runs on every Windows machine. Hot fuck on balls, that beats the 50 minute Typescript BDSM sessions I engage with on CI at work. After the C++ APIs on Windows, doing systems programming at the lowest common denominator let us bend the computer to our own will with less supply chain debt. We are superpowered by C++ in a world where nobody knows C/C++ anymore. I’m writing little tiny bits of NodeJS C++ libraries to integrate new features Electron lacks, and this has worked well. I can add things Electron Just Doesn’t Have. The process is a lot quicker than asking someone on the Electron project to write it for me, or writing it myself and spending my nights and weekends shepherding the itch-scratch PR through the bureaucracy of Electron. I can add value now, goddammit and make our Electron app something that should be an Electron app, because it does actual desktop shit . Here are some good things about C++: LLMs I guess. Fear? Nothing good or defensible as a reason. “Oh it’s dangerous” DRIVING IS DANGEROUS. EATING FOOD IS DANGEROUS. GOING OUT IN PUBLIC IS DANGEROUS. LIFE IS DANGER. You can easily link in legacy C and C++ code There is a lot of C and C++ code you can integrate quickly and well. I chose miniaudio as a lowest common denominator for audio processing (and miniaudio is not ’legacy’, it is a modern project on a conservative stack). Cross platform means it took 2 hours to get a working Linux build out of the code I had originally written for Windows. Notion on Linux works better than Electron would have done the job on Linux because I accidentally got cross-platform by default by writing my code like this. It’s easy to write node.js bridges in it: I even use Objective-C++ for my macOS integrations “Modern” C++ has a lot of features that make it less awful to use – I’m pinned on C++20 and and gives me structural pattern matching. is one of the cleanest JSON libraries I have used in any language and it’s just a header . Compile times are blink-of-an-eye fast. Build stacks are just there on every system. It’s fun to spite people who uncritically adopt shiny things like Rust.

0 views
Andrew Atkinson 1 months ago

Let's Get Down to Business with Rails and PostgreSQL

I’m happy to share that I was a guest on the Rails Business podcast and the episode is now live. Here’s a recap of the topics we discussed. We spent most of the time discussing engineering work last year related to scaling the database workload for peak traffic at Aura where we use Ruby on Rails and PostgreSQL. I’m presenting this information in two places this fall, Rails at Scale Summit in Austin, TX, and the Postgres Summit in NYC. Besides the podcast, you can get more details in these posts: If you’re not able to make those events or prefer to listen to a discussion of the content, then the podcast will have a lot of the same information. Besides the work at Aura, we also checked in on my book High Performance PostgreSQL for Rails , which has now been available in print for two years. Ryan asked about what’s next for the book, and it’s a difficult question to answer. With the availability and quality of AI tooling for software engineers, I don’t see developers buying books as much. With fewer prospective readers, the ROI is less attractive for authors and publishers to commit to the resource-intensive process of creating a book. I’m grateful to have had the opportunity to write a book before the rise of the AI tools. I’m still getting positive feedback from my book which is very fulfilling. Recently I met Madison Sites who’s a reader, and they shared feedback that they’re reading the book as part of the WNB.rb book club . Madison said the book has been helpful for building vocabulary and familiarity with database concepts and implementation details, and that’s helped with database work and better comprehension for conference talks about similar topics. I appreciated hearing about that! We segued into how we’re all using AI tools like Claude in our jobs as software developers, whether it’s writing or reviewing code, doing architectural planning, or myriad other tasks. One of my favorite use cases has been generating infrastructure as code with tools like Terraform. One of the main challenges I’m experiencing is on the review side, what’s expected when it’s AI-generated code in terms of my own comprehension, and how to still provide a quality review given the ambiguity around how much comprehension is needed from me. I also find it challenging to navigate team communication dynamics with AI-generated comments. One concept that’s resonated with me is: don’t be a meat proxy , make sure to do self-reviews and add some value in the chain. I hope you can take a listen to the episode, and please let us know if you have feedback. Thank you! Listen to the Episode 👉 Andrew Atkinson on Rails Business Podcast From Christmas Outage to #1 App Store Ranking: An Aura Frames Postgres Scaling Retrospective Scaling Rails at Aura Frames: Splitting to 8 Primaries and Reaching #1 in the App Store

0 views