Tag Archives: Engineering

Part 2: Generative bidders for ads at Grab

Post Syndicated from Grab Tech original https://engineering.grab.com/part-2-ads-simulation-blogpost

Introduction

Grab runs marketplaces where many important decisions unfold over time, rather than as one-step predictions. Mobility systems need to anticipate how taxi demand and driver supply may evolve across locations and time windows. Food systems need to plan around changing order traffic, merchant capacity, and delivery demand. Ads has the same problem with merchant campaign budgets: traffic quality, user intent, and campaign spend opportunities change throughout the day.

Prediction models estimate what may happen next, such as demand, conversion likelihood, or expected engagement. Many Grab use cases need the system to go further: generate possible future trajectories or action plans, evaluate them against business constraints, and choose a safe path forward.

That is the problem generative models address. They can propose structured futures, such as demand-supply trajectories, order traffic scenarios, or budget pacing plans, conditioned on the current marketplace state and on business goals. Generated futures and generated actions cannot be trusted just because they look plausible. They need to be trained, evaluated, and stress-tested before they influence real users, merchants, drivers, or budgets. This is part 2 of 2. Read Part 1 where we discussed the ads simulator.

Generative bidders for ads

In Grab Ads, the business problem is merchant budget delivery. An ideal campaign spends efficiently across auctions under uneven traffic, winning high-value opportunities while using its target budget. Controllers such as proportional-integral-derivative (PID) controllers are widely used in digital advertising, but they are reactive. They adjust bidding pressure only when a campaign is ahead of or behind its target, and they do not plan how spend should unfold over the next window. To improve ad auction bidding for Grab and its merchants, we propose a generative bidder that plans pacing actions, so campaigns can bid in ways that better serve user experience and business goals. The design follows the diffusion completer-aligner approach described by Li et al. (2025).

A generative bidder produces a short sequence of future pacing actions for a campaign. Ads can then plan budget delivery under marketplace constraints, and use simulation to train, validate, and stress-test those plans before they affect live merchant budgets.

Flowchart of the generative bidder loop. Historical data initializes the bidder, simulated auctions produce trajectories, guardrails decide whether the policy is ready for a live experiment, and live results calibrate the simulator.
Figure 1. Train in simulation, check the guardrails, and only then consider a live experiment.

Part 1 introduced the ads simulator. The simulator does two jobs here. It creates safe opportunities to explore pacing strategies while the bidder trains, and it checks whether those strategies are safe enough for a live test. Training teaches the model to produce plausible, useful pacing plans. Validation checks that those plans survive auction mechanics, budget constraints, delayed signals, and marketplace guardrails.

Why generative bidders need simulation

A traditional budget pacing controller reacts to the gap between how much a campaign should have spent by now and how much it has actually spent. If a campaign underspends, the controller increases bidding pressure. If it overspends, the controller backs off. The pattern is reliable, and it is reactive.

A generative bidder plans ahead. Instead of one adjustment for the current auction, it generates a sequence of pacing actions for a short future window, on the order of tens of minutes. The plan is conditioned on campaign state, time, budget, billing type, current fulfillment progress, the allocation target, and return on ad spend (ROAS) goals.

The simulator does more than score the bidder after training. It also generates training data. Candidate pacing plans run through simulated auctions, and the resulting trajectories, budget movement, fulfillment progress, ROAS, and guardrail metrics are recorded as training examples. The Generator learns which pacing sequences are realistic. The Aligner learns how those sequences affect delivery and efficiency.

The system can then propose different spend shapes over the next window. One plan may spend steadily. Another may hold back early and bid more aggressively later. A third may increase pressure when the model expects higher-value traffic. Simulation lets us explore these alternatives safely, learn from their outcomes, and test the resulting bidder before it affects real merchants.

Core components: Generator and Aligner

Diagram of the Generator and Aligner bidding architecture. Campaign context feeds a diffusion model that proposes 30-minute pacing plans. The Aligner predicts fulfillment, refines candidates, and the planner selects one plan to serve.
Figure 2. Generator and Aligner architecture.

The bidder uses a generate-then-align architecture. The Generator proposes a 30-minute pacing plan, represented as a sequence x = [p₁, …, p₃₀], where each pᵢ ∈ [0, 1] and is the pacing action for one minute. The Aligner evaluates each plan by predicting its final fulfillment progress and ROAS.

Generator

Let x₀ be a real pacing sequence from historical logs or from simulator-generated training data, and let c represent the campaign context and target outcomes. During training, the diffusion process adds Gaussian noise to x₀:

xₜ = √(ᾱₜ) x₀ + √(1 − ᾱₜ) ε, ε ~ 𝒩(0, I)

The Generator learns to predict the noise that was added:

L_gen = 𝔼[‖ε − εθ(xₜ, t, c)‖²]

At serving time, the Generator starts from random noise and reverses this process to produce candidate pacing plans. Classifier-free guidance steers generation toward the requested targets:

ε_guided = ε_uncond + s(ε_cond − ε_uncond)

Aligner

The Aligner receives the campaign context and a candidate pacing trajectory, then predicts the expected outcome:

ŷ = Aϕ(c, x)

The planner compares these predictions with the desired campaign targets:

J(x; c) = Σₘ wₘ ρ(ŷₘ − yₘ*)

Here, yₘ* is the target for metric m, w_m controls its importance, and rho is an error function. The target metrics may represent revenue, budget utilization, or other business objectives.

Inference-time refinement

Because the Aligner is differentiable, the planner can refine the pacing actions at inference time without changing the Generator or Aligner weights. For candidate j at refinement step k, it computes the gradient of the objective with respect to the pacing trajectory:

gⱼ⁽ᵏ⁾ = ∇ₓ J(xⱼ⁽ᵏ⁾; c)

It then updates the trajectory in the direction that reduces the predicted error, and clamps each action to [0, 1]:

xⱼ⁽ᵏ⁺¹⁾ = clip(xⱼ⁽ᵏ⁾ − αₖgⱼ⁽ᵏ⁾, 0, 1)

The planner generates and refines multiple candidate trajectories, then selects the one with the lowest target error:

x* = argminⱼ J(xⱼ; c)

The Generator produces realistic and diverse pacing plans. The Aligner makes them goal-aware by refining them toward defined targets. The simulator supplies the historical and simulated trajectories used to train both components, and it is the environment used to validate the refined plans.

Training: from historical behavior to simulator-driven learning

Training starts with historical behavior. Production data shows how campaigns paced spend under existing controllers. This phase gives the bidder a safe baseline: daily traffic rhythms, campaign-level differences, budget pressure, and the relationship between pacing actions and observed outcomes.

This is behavioral cloning. It is a useful initialization, and it can also reproduce limits in the historical data or in the existing control strategies. The model should learn from production behavior without being restricted to copying it.

The simulator is what lets training move past that baseline. In simulator-driven training, candidate bidders run against replayed historical traffic. The loop collects trajectories and outcomes, and uses those outputs to improve the next model version. Weak strategies can fail offline. Promising strategies can be reinforced across many simulated campaign states. The model can explore pacing plans that would be too risky to test directly in production.

Training at scale with the simulator and Ray

Simulator-driven training is a modeling problem and a distributed systems problem. A useful training round has to replay many historical traffic slices, run candidate policies through the simulator, collect trajectory-level outcomes, train the Generator and Aligner, and register a new model version. Doing that serially would make iteration too slow.

Ray, a distributed computing framework, gives this loop its throughput. A single simulator run can replay one day of traffic and process multiple auction requests. A training round can launch independent simulator workers across different historical dates, campaign slices, or candidate policy versions. Each worker loads its assigned auction data, runs the bidder through replayed traffic, and writes pacing trajectories, spend movement, fulfillment progress, ROAS, and guardrail metrics back to storage.

Ray runs this orchestration as a cluster workload, rather than as a notebook or a one-off batch script. It allocates resources across simulation and training workers, keeps independent replay jobs running concurrently, and gives the loop a way to retry or replace failed work. Inside each simulator, auction processing can still use local parallelism for groups of auction requests. Ray handles parallelism across days, markets, model candidates, and training phases.

The output of this fan-out becomes the next training dataset. The Generator learns from pacing trajectories. The Aligner learns from observed end-of-window outcomes. After training, the updated models are registered as versioned artifacts that can move into validation.

The combined simulator and Ray layer matters for three reasons:

  • Scale. The model can learn from many simulated days or campaign states in one training round, instead of waiting for sequential replay.
  • Diversity. Parallel simulation can cover different traffic patterns, markets, campaign types, and policy variants, which reduces the chance that the model overfits to one historical slice.
  • Repeatability. Each training round can be tied to a specific dataset window, simulator configuration, model version, and validation report, which makes failures easier to diagnose.

The training loop

The training loop has seven steps:

  1. Start with historical production data to learn a safe baseline.
  2. Train the initial Generator and Aligner on observed pacing sequences and outcomes.
  3. Launch parallel simulator runs across campaign states, traffic patterns, dates, markets, and candidate policies.
  4. Let the candidate bidder act inside simulated auctions.
  5. Collect trajectories, including bid plans, auction responses, budget movement, fulfillment progress, ROAS, and guardrail metrics.
  6. Train an improved model from successful and failed strategies.
  7. Register the updated Generator and Aligner as versioned artifacts for validation.

Generation, execution, and learning stay connected. The model does not imitate old pacing behavior once and then stop. It proposes plans, the simulator shows the consequences, training absorbs those consequences, and the next model version gets another chance to plan better.

Validation: from model metrics to marketplace safety

Training asks whether the model can learn. Validation asks whether the learned policy should be trusted.

For generative bidders, validation has to happen at several levels. A model can have a good validation loss and still be unsafe in the auction loop. A generated sequence can look realistic and still underspend. An Aligner can predict well on historical trajectories and still misjudge trajectories from a new Generator. Validation is a separate gate after training, not a side effect of it.

Level 1: dataset and model validation

The first validation layer checks whether the training pipeline and the model are internally sound.

For the Generator, the training code keeps a time-based validation split and logs validation loss, the mean difference of reconstructed sequences, and distribution divergence. The evaluation review adds visual trajectory inspection, distribution fidelity checks, Wasserstein distance between generated and real pacing sequences, and conditioning sensitivity tests. These checks answer basic questions: do generated pacing plans follow real pacing rhythms, do their values occupy a plausible range, and do they change when campaign context changes?

For the Aligner, validation tracks whether the model predicts fulfillment progress and ROAS on held-out windows. It logs fulfillment and ROAS losses, mean absolute error (MAE), and mean squared error (MSE). These metrics matter because the Aligner guides candidate selection. If it overpredicts fulfillment progress, the planner may treat a campaign as on track when the campaign is underspending.

This layer is necessary, and it is not sufficient. It validates the learned components in isolation. The next layer validates the bidder as a decision system.

Level 2: simulator validation against auction dynamics

Replay-day charts comparing a generative bidder with a PID baseline on budget delivery through the day, the direction of auction outcomes, and guardrail breach frequency.
Figure 3. Simulator-based validation.

The simulator validation layer replays the bidder inside the auction environment.

The question changes from whether the model predicts well to what happens when this bidder controls pacing over time. The simulator compares the generative bidder with the existing PID-style pacing baseline under the same historical traffic and campaign conditions. It measures budget adherence, ROAS, order value, spend smoothness, early budget exhaustion, and guardrail violations, to determine that the generative bidder improves on PID without compromising delivery or efficiency.

Level 3: stress testing and guardrails

A generative bidder also needs scenario validation. The simulator can stress the policy under cases that may be rare or risky in live traffic:

  • Sudden traffic spikes during high-value periods.
  • Campaigns that are behind target late in the day.
  • Campaigns with sparse or delayed conversion signals.
  • Markets with different budget and currency behavior.
  • Generated plans that approach budget exhaustion too early.

These stress tests make safety a training and release gate. The bidder should do more than look good on average. It should fail gracefully when the market surprises it.

Deployment: staged live handoff and calibration

Deployment comes after the training and validation gates. A candidate first passes dataset and model validation. It then passes simulator validation against the baseline and the guardrails. It then enters a scoped live experiment.

At serving time, the planner uses the trained Generator and Aligner to create short-lived pacing plans. It generates multiple candidate trajectories, refines them with the Aligner, selects the best plan, executes that plan for the next window, and refreshes the plan when the window expires. The deployed system keeps the same generate, align, select, and refresh pattern used in offline development, under live production constraints.

Live experiments remain the source of truth. The simulator can reduce risk, narrow the candidate set, and expose bad policies early. It cannot replace production evidence. After a live result lands, the gap between simulated and live outcomes becomes calibration data for the next simulator version.

That feedback matters because simulator fidelity moves. As the bidder enters regimes that historical controllers never explored, the simulator has to keep learning too.

Conclusion

This work explores a shift from models that primarily predict outcomes toward generative algorithms that propose candidate actions, plans, and strategies. The framing is specific to this system. It does not describe a company-wide direction.

Many Grab marketplace problems unfold over time. Mobility systems need to reason about future demand and supply. Food systems need to anticipate order traffic and capacity. Ads systems need to decide how merchant budgets should move across uneven traffic while protecting ROAS, revenue, and user experience. In each case, the opportunity is to generate possible futures or action plans and test which ones are safe and useful, not only to predict what may happen.

For Ads, generative bidders are an early example. Instead of reacting auction by auction, a bidder can generate a short pacing plan for the next window, conditioned on campaign state, budget pressure, traffic context, and business goals. The simulator is the environment where these generated plans can be trained, compared, stress-tested, and filtered before they reach production.

The longer-term direction is to make this simulation-to-live loop a standard path for generative algorithms. Offline simulation can identify promising candidates, reject unsafe ones, and expose where a strategy is sensitive to specific traffic slices. Live experiments can then validate a smaller, stronger candidate set and feed real outcomes back into simulator calibration.

The goal is to build the infrastructure that lets Grab move safely toward generative decision-making: generate broadly, validate rigorously, launch narrowly, and learn continuously from production.


We gratefully acknowledge Allen Lin and Jianning Zhang from Grab’s DNA Data Science team for sharing valuable insights into Grab’s advertising systems and data, and for helping validate the simulator’s fidelity. We also thank Ruike Zhang, Richard Ryu, Padarn George Wilson, and Weilun Wu for their support and guidance throughout this work.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

References

Li, Y., Gao, J., Jiang, N., Mao, S., An, R., Pan, F., Zhao, X., An, B., Cai, Q., and Jiang, P. (2025). Generative auto-bidding in large-scale competitive auctions via diffusion completer-aligner. arXiv. https://doi.org/10.48550/arXiv.2509.03348

Probing DNS at Cloudflare

Post Syndicated from Doug Aaser original https://blog.cloudflare.com/probing-dns-at-cloudflare/

Imagine this: you’ve just pushed a release. All the unit tests passed and your dashboards are green. You sit back to relax but then suddenly your phone starts blowing up: prod is broken.

This is something the Cloudflare DNS team has experienced firsthand. In one rollout of the service that publishes DNS records to our edge, a scheduling bug let some record changes sit unpublished for hours. The service stayed up and was healthy, but new hostnames were slow to resolve and certificates couldn't be issued until the bug was squashed.

DNS failures are hard to catch because they are slow, spread across the network, and partial in where they cause impact. We needed to figure out a way to test DNS the way customers experience it: constantly, from every data center, and against production.

For us, the answer was to extend Flamingo, the end-to-end testing framework we were already using to run hundreds of millions of tests a day against Cloudflare's edge. This post covers how Flamingo's modular design lets us add DNS support, how we measure propagation, and how those measurements now decide whether a release goes ahead or gets rolled back.

A little background

At Cloudflare we’re obsessed with improving performance and safety for our customers. It’s crucial that our code is tested constantly, both at scale and against the real Cloudflare edge that our users operate in. That’s one reason why we created a tool called Flamingo: to measure the behavior of our production environments and make sure that code in lower-tier environments behaves as expected.

We’ve already written a little about how this tool has been used in the upgrades to our CDN stack. However, this is only a small portion of how we use Flamingo internally. One of the features of Flamingo is its modular architecture that enables teams to extend the capabilities of the tool to speak other networking protocols. In our case, we wanted to use these modular capabilities to test DNS.

What is Flamingo?

Testing is hard. Testing at scale, when you have a widely distributed system, is even harder. There are many complex pathways that requests take and multiple systems that each network request must traverse before making its way to the origin. Unit testing alone is not nearly enough for this. We need to run constant automated testing against real systems and measure the outcomes of those requests to make informed decisions on the health of a service.

Enter Flamingo. Originally built around complex multi-step HTTP testing, its capabilities and scope have increased substantially over the years. Flamingo is built from the ground up with Cloudflare’s infrastructure in mind. We built a control plane and scheduler that let teams target specific environments, data centers, or percentages of metals. We needed to integrate with custom reporting, metrics, and analytics tooling. Additionally, it needed to be a tool with predictable performance and run well on bare-metal servers in resource-constrained environments.

Being delightful

When we’re building internal tooling like this, we strive to create a delightful developer experience. Internal tooling should be as easy as possible to use, but also powerful enough to handle over 80% of all use cases. And in order for a new edge acceptance test framework to be successful, it needs to be built in such a way that it forces teams to follow common guidelines and build reusable scripts in an environment that is stable, scalable, and manages complexity.

One thing that is not delightful is debugging a test. If you allow a user to write tests in a traditional programming language, when their test fails they then both need to debug the upstream system being tested and the test itself. This is why we built Flamingo to use a custom domain-specific language (DSL) consisting of a simple setup-request-response format.

For example, let’s imagine that we want to make sure we are redirecting all unencrypted traffic to its encrypted counterpart.

TEST test-redirect
SET $hostname www.cloudflare.com

GET "http://$(hostname)/"

ASSERT STATUS IS 301
ASSERT HEADER Location IS "https://$(hostname)/"

Here we can see the power of the DSL. In five lines of code, we have a script that can run anywhere on Cloudflare’s edge and scale to thousands of requests per minute. We can take the data produced from the millions of data points generated from this and turn those into a graph defining how our service is actually performing in the real world.

Taking the setup-request-response test format from above and modifying it slightly allows us to use Flamingo for more than just HTTP testing. Instead of the middle step being a request, we can now look at it as an action. Now we’ve changed our system from something that makes HTTP requests into something that can perform any action for which we’d like to measure the outcome.

In Flamingo we call these modules and have put immense effort into making them as easy as possible for anyone to write. Flamingo is written in Rust, due to its consistent performance characteristics and strong type system. The type system in particular lends itself to this modularity, by allowing us to use strongly-typed enumerations for input and output in the Flamingo action runner:

pub enum Action {
  Query {
    method: String,
    url: Expression,
    parameters: Vec<http::QueryParameters>,
  },
  DnsQuery {
    query_name: Expression,
    query_type: Expression,
    parameters: Vec<dns::DnsQueryParameters>,
  },
}

pub enum ActionOutput {
  Http(http::FetchResponse),
  Dns(dns::QueryResponse),
}

pub type ActionHandlerFunction = Arc<
  dyn Fn(
      Action,
      Arc<Ctx>,
      InterpreterConfig,
    )
      -> BoxFuture<'static, Result<ActionOutput>>
    + Send
    + Sync
    + 'static,
>;

pub type ActionHandlerLUT = Arc<
  dyn Fn(&Action) -> ActionHandlerFunction
    + Send
    + Sync
    + 'static,
>;

What we’ve done here is decouple the logic for performing an action (in this case an HTTP request) into a dynamically dispatched function that we can then call independently of other actions. This leaves things like test scheduling and resource management as higher-level operations that someone implementing a module doesn’t need to worry about. All the author needs to focus on is the logic.

pub async fn query(
  action: Action,
  ctx: Arc<Ctx>,
  cfg: InterpreterConfig,
) -> Result<ActionOutput> {
  let Action::Query {
    method,
    url,
    parameters,
  } = action
  else {
    bail!("Invalid action for module-http::query: {action:?}");
  };
  ...
}

pub async fn execute_module<F>(
  ctx: Arc<Ctx>,
  cfg: &InterpreterConfig,
  handler_lut: F,
) -> Result<ActionOutput>
where
  F: (Fn(&Action) -> ActionHandlerFunction),
{
  let func = handler_lut(action);
  let action_out = (func)(action.clone(), ctx.clone(), cfg.clone()).await?;
  ...
}

Using Flamingo to probe DNS

The adage says that when issues arise, it's always DNS. Like many jokes, there is always a kernel of truth behind it. DNS is an incredibly important piece of the Internet, and since it relies on a complex network of interconnected sources of truth, it can become easy for a single misstep to cause a storm of failures.

DNS can be a particularly finicky system due to its hierarchical nature. When you change a DNS record for a Cloudflare zone, for example, said record needs to be propagated to the authoritative servers such that the updated record becomes widely available. To reduce latency, records are stored in physically closer caches. These records have a time to live (TTL) associated with them that tells the local DNS cache how long before it needs to refetch that record from the authoritative server. Any delays will impact time-sensitive operations like certificate issuance and traffic failover.

We’ve already mentioned that we built Flamingo for extensibility. One of the first and most impactful modules in use today was built specifically for this use case. Our team was able to add code that extended Flamingo such that instead of sending HTTP requests, we send DNS queries. By doing so we got everything else for free. No need for the DNS team to worry about managing a new probing service. No need for them to have to integrate with our reporting pipelines. It all just worked.

To probe DNS, we measure how quickly customer record changes propagate to authoritative nameservers and the public resolver (1.1.1.1). The test continuously updates a TXT record with a timestamp and queries three authoritative nameserver IPs and 1.1.1.1 from every data center, asserting freshness within 90s (authoritative) and 600s (resolver).

TEST test-propagation-delay-direct-108-162-193-62
MOD dns

SET $hostname "some.probe.domain"
SET $authNs 108.162.193.62:53 # amir.ns.cloudflare.com

QUERY $hostname TXT
TARGET $authNs

ASSERT DNS.RCODE IS NOERROR
ASSERT DNS.FLAGS CONTAINS AA
ASSERT DNS.ANSWERS[0] GT SUBTRACT(TIMESTAMP(), "90")

Catching bugs (SLO and steady)

To ensure that our many systems are operating within expectations, we define what are called service-level objectives (SLOs) for observing things like availability or latency. SLOs are a percentage of some metric that is used as a target. Additionally, SLOs are measured through service-level indicators (SLIs) which are the actual series of measurements focused on the end-to-end experience that a user has when interacting with a system.

By constantly sending synthetic Flamingo traffic through our production systems, we can begin to then use that information to build a picture of what our actual end users are experiencing — and provide that data for our SLOs. When that synthetic traffic encounters issues then we can be pretty confident that Cloudflare customers are also hitting issues and triage accordingly.

Once we have this information, it allows us to make informed decisions when releasing a service. SLOs operate in terms of error budgets and burn rates. An error budget is the percentage of downtime that a service is willing to tolerate while the burn rate is the rate of change in that budget at any given time. This allows for an automated system to understand the severity of an issue. For example, burning 10% of your error budget over a three-day period might be some long running issue that, while not urgent, is affecting customers and needs to be dealt with. But if you were to burn 10% of your error budget within an hour, that means an incident is occurring and customer impact will be substantial if not fixed immediately.

Using these numbers, we can look at our SLOs while deploying and make informed decisions on the health of a service. Based on that information, we can tell our releasing systems to either promote a change or roll it back.

The road ahead

By moving DNS monitoring to Flamingo, we’ve created a system that can proactively detect DNS issues before they have the chance to spread to the rest of Cloudflare’s edge. If Flamingo detects a spike in propagation latency in a specific canary data center, we can automatically halt the rollout of a new software version before it impacts the rest of the Internet.

DNS is just the start for extending Flamingo. We currently have modules for testing TCP, UDP, WebSockets, and several more. Having a tool for quickly testing and monitoring services has enabled teams to deploy large changes safely without the need for a human to keep a constant watch.

If this kind of reliability engineering interests you, check out our careers page for open roles.

How Grab built Scarlet: the AI teammate that turns a Slack message into a production data pipeline

Post Syndicated from Grab Tech original https://engineering.grab.com/how-grab-built-scarlet-blog

Introduction

In the blog From firefighting to building, we described the agents our Analytics Data Warehouse (ADW) team built to take routine work off data engineers. Scarlet was the Enhancement Agent in that post. It read a ticket, wrote the change, and opened a merge request (MR) for an engineer to review. A routine enhancement dropped from about a day to one or two hours.

Figure 1. A pipeline change without Scarlet.

Then other teams asked for it, and four limits became clear:

  • One team only: Scarlet’s repository and conventions lived in a single system prompt sent on every request. A second team meant forking the bot.
  • No proof the data was right: Scarlet could run a change in a test environment, but nothing checked whether the output data was correct. That hour of manual validation still fell to a person, and it was the step most often skipped.
  • Shared access: Early versions of Scarlet did not tie each action to the permissions of the person who requested it.
  • Slack only: Every request needed someone to type it into a thread.

This post is about closing those gaps. We rebuilt Scarlet around a short core prompt and a library of skills: Markdown documents, one per capability or per team, loaded only when a request needs them. The prompt shrank about 25 times, and teams now review that knowledge like code. Scarlet also tests the data its changes produce, runs under the asker’s own permissions, and takes work from Jira tickets and other agents.

Since this version reached production in May 2026, the repositories Scarlet ships to have grown about four times, weekly usage has roughly tripled, and the merge rate has climbed from about half to more than four in five. The merge still belongs to a person.

What Scarlet does

To recap our initial blog: an engineer pastes a ticket into a Slack thread, Scarlet finds the repository and pipeline, checks the catalog, writes the change, and opens an MR for a human to review. That loop has not changed. Neither has the boundary: Scarlet has no merge or approve call, so merging stays with people.

Everything around that loop has changed.

In the thread:

  • A plain-language description is enough. No ticket needed.
  • Scarlet posts a plan before it touches a file.
  • A live plan card shows each tool call as in progress, complete, or failed, with a cancel button.
  • Follow-ups keep the earlier context, so “add one more column” needs no repetition.
  • Attached files load as reference material, never as instructions.

In the MR: a structured description, a bot label, and the requester tagged and assigned. If the branch already has an open MR, Scarlet updates it instead of opening another.

Figure 2. Scarlet’s live plan card during a pipeline build.

Scarlet now also works with the data catalog and the data quality platform, and handles far more scheduler actions than before. On each of them it follows one rule: show what it is about to do, then wait for a yes.

  • Catalog and data quality changes: Scarlet posts the exact update it will write and waits for approval.
  • Scheduler actions: Scarlet spells out which host, which directed acyclic graph (DAG), which run, and what it will do, then waits for approval.
  • Read-only requests: no approval needed.
  • Data contracts: Scarlet will not create one for a table whose quality checks are failing. A data contract tells downstream users the table is safe to depend on, and a table with failing checks is not.

Scarlet also answers questions about the data, such as how many rows landed yesterday. It runs those queries as the person asking and returns only aggregates, never per-person rows, under a hard cap that holds even if the model ignores its instructions.

How the agent plans and acts

A request passes through four layers:

  1. Slack carries the conversation and progress updates.
  2. A reasoning loop picks the next action.
  3. The skill library supplies the instructions for the current team and workflow.
  4. An action layer reaches Jira, GitLab, Airflow, Google Docs and Sheets, and our internal data platforms.
Figure 3. How a Slack message becomes a merge request.

The first post described streamlining more than thirty verbose tool descriptions. Scarlet now goes further. Each internal platform sits behind a Model Context Protocol (MCP) bridge with two tools, one to list operations and one to call them, and schemas load only when needed. A platform with dozens of operations adds nothing to a request that never touches it.

Scarlet has two identities, split by what it touches:

  • Data platforms (catalog, data quality, jobs, scheduler): Scarlet has no credentials of its own. Each operation runs as the requesting user through a short-lived token from their sign-in, so anything they cannot touch fails for Scarlet too.
  • Source control: operations run as the Scarlet bot, so a machine-authored MR is easy to spot.

When a user asked how its access worked, Scarlet summed it up: “I can only do what you can do. I’m an accelerator for your own permissions, not a bypass around them.”

Every reply ends with a footer linking to its full trace, so a reviewer can see exactly what Scarlet did and why.

The skill library

Scarlet’s core prompt contains no workflow detail. It tells the model to load the relevant skills before acting. Skills describe how to do the work, and tools do it.

Each skill is a Markdown document that defines one capability or one team’s conventions, plus the skills it depends on. The table certification skill, for example, pulls in the catalog and data quality skills it relies on.

The library has four kinds of skill:

  • Platform skills cover common operations, such as reading tickets, finding tables, and opening MRs.
  • Routing skills work out which team and repository a request belongs to.
  • Repository skills record a team’s repository, schema ownership, scheduler, labels, and conventions.
  • Workflow skills run end-to-end tasks: building pipelines, rewiring sources, certifying tables, validating data changes, and reviewing MRs.
Figure 4. Skill resolution.

A skill goes through the same life cycle as code:

  1. An author writes or changes a skill and opens an MR. Scarlet can draft this MR itself.
  2. Reviewers approve it the way they review code.
  3. A pipeline validates the skill and publishes an immutable bundle.
  4. At startup, Scarlet activates one bundle version and writes that version into its prompt, so every answer traces back to the exact instructions that produced it.

A new team joins by adding one repository skill. The library has roughly tripled since July. Much of that growth is team skills, and several of them were written by the teams that use them.

Validating the data

Continuous integration (CI) proves that the code runs. It cannot prove that the data is right: a join that silently drops rows, a column that is suddenly half null, or a swap that overwrites yesterday’s output all pass CI. Manual checks were easy to deprioritize, because they take longer and typically require familiarity with both Structured Query Language (SQL) and the tables involved.

Scarlet now tests the data as part of the change. This job used to belong to a separate validation bot, and we folded it into Scarlet. The flow:

  1. During CI, our data platform runs the candidate change in an isolated environment and publishes a manifest linking the commit to the table it produced.
  2. Scarlet reads the manifest, so it has real candidate output before anyone reviews the MR.
  3. From the change, Scarlet works out what to compare: the target table, the changed columns, and the table’s keys and partitions.
  4. It runs its checks against the current production table.
  5. It posts a verdict of pass, fail, or inconclusive, with evidence for every check, bound to the exact commit it tested.

The checks:

  • Schema and type differences.
  • Row counts.
  • Duplicates and key reconciliation.
  • Null rates and column profiles.
  • Numeric statistics such as minimum, maximum, mean, and spread.
  • Row-level differences between the two outputs.

The rules:

  • The kind of change sets the mandatory checks, and requesters can add their own scenarios in the ticket.
  • Inconclusive counts as a failure.
  • If the change moves after testing, the verdict expires and the checks run again.

Automated checks can make MR validation and table comparisons less time-consuming than manual review.

We are extending the same flow past the merge. Scarlet will watch the first production run after an MR merges, rerun its checks against the live output, and, if they fail, raise a revert MR for a human to approve.

Figure 5. Testing a change’s data.

Beyond Slack

Not every request starts with a Slack message anymore. There are three ways in:

  • Slack thread: the flow described above.
  • Jira label: within about five minutes of a ticket being labeled for Scarlet, it picks the ticket up, starts a thread in its channel, tags the assignee, and works the ticket through to the MR.
  • Command line and run application programming interface (API): engineers use Scarlet from a terminal, and coding assistants such as Codex and Cursor call it as a tool. The agent, its skills, and every credential stay on the server, and sign-in pauses work as they do in Slack.

Seeing it in action

The first post walked through a single column change for our own team. These three cases show new kinds of work and new teams.

Our own first pipelines

  • Ask: onboard a new finance source system into the data lake, which needed many similar pipelines. An engineer described the task in a single message.
  • What Scarlet did: read the source schema from the catalog, generated the transformation, DAG, and dependency files, and opened an MR within 30 seconds of the go-ahead. CI passed about five minutes later.
  • Result: every pipeline that week passed CI on the first attempt, and almost all of the generated code shipped without rework. We estimate the work took around 6% of the engineer time it would have taken by hand.

The first merge request outside our team

  • Ask: an analytics engineer on a commerce team, in their first week with Scarlet, wanted five fields added to a clickstream table.
  • What Scarlet did: opened the MR, then its own review pass flagged that the field names broke the upstream team’s convention. The engineer picked the convention, and Scarlet updated the MR and the ticket.
  • Result: a reviewer merged it the next day.

A team onboarded mid-request

  • Ask: an engineer on a lending analytics team, using Scarlet for the first time, wanted a scheduled job changed for a team Scarlet had never been set up for.
  • What Scarlet did: when the engineer typed “onboard my team to Scarlet”, it drafted the team’s skill as an MR. After a single sign-in, it updated the job under the engineer’s identity and ran its post-change checks.
  • Result: the skill MR merged the next day, and the job change went through under the engineer’s own permissions.

Lessons from production

Templates for predictable structure

What happened: during one migration, Scarlet produced a large MR that passed CI and failed at runtime. The model had guessed part of the job configuration.

What we changed:

  • Deterministic scaffolds for predictable structures. They run the platform’s own code generator and validate the output against a contract.
  • A Slack wizard for teams that prefer forms. It never calls the model and captures all the necessary details as required.
  • A validate, lint, fix loop for generated SQL and configuration. It stops after a few failed attempts and asks a human.
  • The model keeps only the work that needs judgment: mapping columns, writing transformations, explaining failures.

Sign-in as a pause

What happened: when Scarlet acts as the user, some platforms need that user to sign in first. At first, hitting one of those mid-run ended the workflow, and replaying the request lost the progress.

What we changed: sign-in is now a pause. The run checkpoints at a LangGraph interrupt, and the sign-in callback resumes it from that point while the same plan card keeps updating.

Measuring without reading conversations

What happened: the first post’s feedback loop ran on reviewers rating each answer in Slack. Scarlet’s output is an MR reviewed in GitLab, so that loop did not carry over, and after launch we could not say who used Scarlet, for what, or how often it succeeded.

What we changed: a recorder that captures metadata from the tool stream (requester, source, skills, tools, duration, outcome, intent) without storing conversations. Request text is opt-in, and anything that looks like a credential is redacted. The figures below come from it.

Impact

These figures come from the usage events Scarlet records.

Figure 6. Weekly usage and merge rate, May to September 2026.
  • Weekly usage held steady from July to mid-August, then climbed. In the week of 7 September it reached about three times the usual request volume from about twice as many users, and the following week held near twice the usual level.
  • The share of monthly users who came back for a second week rose from about 42% in July to 56% in August and stayed above 50% in September. The top user’s share fell from nearly half of all requests to under 10%.
  • Repositories with a Scarlet MR grew about fourfold from May to September, and monthly MRs opened grew more than fourfold from June to September. The merge rate rose from about 50% in May to over 85% in September. Early September alone produced more merged code than the whole of August.

The mix of requests changed as the skill library grew:

  • Table discovery grew fastest, more than six times from July to September, as new teams explored the catalog before asking for changes.
  • By September about half of all requests were questions about the data, not changes. Answering under the asker’s own permissions turned out to matter as much as the merge boundary.

Current limits

  • Long threads degrade answer quality, and a very large request can exceed a single model turn. Starting a new thread helps once older context stops being useful.
  • Coverage gaps: schema and freshness checks only, certification for production tables only, and source rewires stop for a human when fewer than about 70% of columns can be mapped.
  • Data testing covers code-pipeline changes. Batch-job changes still need an isolated test environment first.

The biggest open problem is uncertainty. When repository conventions do not settle a configuration choice, Scarlet sometimes proceeds without asking. The next step is to make that rule explicit in the skills and check it with regression tests on every release.

Takeaways

Slack made the work visible. The skill library made it maintainable: a new repository no longer needs a new agent, and teams review the files that hold their conventions. If you are building something similar, keep the model for the judgment calls and write every convention down as a file someone can review.

What’s next

The first post drew the line at anything that changes production: those actions wait for a human. With CI and data validation now in place, we think that line can move for routine work. Now that requests can start from tickets or other agents, every Scarlet MR will pass through one risk-based approval gate:

  1. CI passes.
  2. Scarlet’s data validation returns pass. A fail or inconclusive verdict goes to a human.
  3. The change is routine. New pipelines, rewired sources, and data contract changes always go to a human.
  4. A change that passes all three checks could move through review faster, with an engineer still making the final call to merge.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Part 1: Simulation-first AI experimentation for ads at Grab

Post Syndicated from Grab Tech original https://engineering.grab.com/part-1-ads-simulation-blogpost

Introduction

Ads delivery at Grab is increasingly an artificial intelligence (AI) decisioning problem. Every ad opportunity requires the system to infer user intent, predict engagement, balance advertiser returns, platform revenue, and user engagement, respect campaign budgets, and decide which ads should appear in a highly constrained product surface. As our ads systems become more complex, the range of bidding, ranking, and pacing strategies we need to evaluate grows with them. To continue improving quickly and safely, our approach to experimentation had to evolve: test more hypotheses offline, filter them against business and user guardrails, and reserve live traffic for the most promising ideas.

Live A/B tests remain the gold standard for testing changes, but they consume real traffic, take time to gather clear signals, and expose users and advertisers’ budgets to unproven ideas. At Grab, we built an offline ads simulator to evaluate AI-driven bidding, ranking, and pacing strategies before they reach production. The simulator lets us replay historical ad opportunities, test alternative decision logic, measure business and user guardrails, and send a smaller, better-vetted set of configurations into live experiments, so each live test starts from an informed position rather than an open search.

This is a two-post series. A second post covers how we extended this environment to train and validate generative bidders.

How an ad auction works

A simplified ad auction begins when a consumer action creates an ad opportunity: a user opens a food listing page or searches for a cuisine. The system gathers eligible ad candidates from merchant campaigns and evaluates them against the current context.

Each campaign decides how much to bid, drawing on its own configuration, its delivery state, and an estimate of how the user is likely to respond. The auction then ranks candidates, selects winners, and displays them. After the user sees or interacts with the ad, the campaign budget and performance metrics are updated.

This is a sequential decision-making problem. A decision made at noon can affect how much budget remains in the evening. For example, bidding too aggressively early in the day may exhaust a campaign’s budget and prevent it from competing for better opportunities later. A simulator is therefore useful because it evaluates how decisions compound over time, rather than assessing each auction in isolation.

Workflow diagram of an ad auction from opportunity to budget update
Figure 1. Workflow of an ad auction.

The simulation-first experimentation workflow

Why we built an ads simulator

When improving our ads system, we often begin with several candidate changes (hypotheses). A candidate is a proposed version of the system that we want to evaluate. There could be different parameter configurations for the current setup, a change to an existing component such as ranking or pacing, or an entirely new component such as a bidder.

Each candidate represents a “what if” question:

  • What would happen to Return on Ad Spend (ROAS) if we paced campaigns more aggressively throughout the day?
  • What would happen to conversions if we change the balance between ads and organic content?
  • What would happen to ad spend if we use a new type of bidder for our ad campaigns?

Historically, we answered such questions using offline analysis, domain intuition, and A/B tests. These approaches work well for incremental changes, but become limiting when the search space grows. A single parameter can require many possible values. A policy can vary by time of day, city, campaign type, or other contextual features. A machine learning (ML) model can propose strategies that have never appeared in historical logs.

Live experimentation can also be noisy when metrics are strongly affected by daily traffic conditions. The same parameter configuration could look better or worse depending on the day on which it is tested. Testing a large candidate space in production would consume substantial traffic, take considerable time, and expose users and advertisers’ budgets to unproven changes. These changes expose the business to risks, and can be mitigated by the use of our simulator.

The simulator allows us to evaluate these candidates first by replaying them across historical days, placements, and traffic conditions. Candidates that perform well only in a narrow slice can be filtered out, while those that remain stable and satisfy business and user guardrails can be shortlisted for live testing. The corresponding configuration or system change can progress to a focused A/B test.

The simulator does not replace live A/B tests. It improves the hypotheses that go into them, so each live experiment starts from a more informed position.

Diagram of the simulation-first experimentation workflow
Figure 2. Simulation-first experimentation workflow.

What the simulator replays

The simulator replays historical opportunities using the campaign, traffic, and contextual data observed in production. A data preparation step transforms these records into a consistent replay dataset.

For each opportunity, the simulation engine applies the candidate bidding and ranking strategy, determines which ads would be shown, and probabilistically generates downstream user responses from calibrated engagement models. It then updates campaign state before processing the next opportunity. This sequential replay captures how each decision affects later auctions and records the resulting campaign, advertiser, and platform metrics.

The system is modular by design. Each component (sampling, bidding, ranking, pricing, and metrics) is independently configurable. A team can swap out a bidding strategy without touching the ranking logic, or test a new metric without rerunning the pipeline from scratch. This makes it straightforward to keep the simulator in step with production as new features are built and existing ones evolve.

Making the simulator trustworthy as an AI evaluation system

For AI-driven ads systems, a simulator is useful only if teams can trust its signals enough to make experimentation decisions. We treat simulator fidelity as an engineering requirement, not an assumption. The goal is not to predict every live outcome precisely, but to make offline comparisons meaningful enough to decide which model, policy, or strategy should move into live testing.

We validate this through regular fidelity checks across two levels. The first is mechanism level: each deterministic component is validated against production logic to ensure the simulator applies the same rules in the same order. The second is outcome level: we aggregate metrics from production against simulator outputs with production configurations. Key metrics are compared across equivalent traffic slices to confirm distributions align. Where gaps appear, they are investigated and the relevant component is updated before the simulator is used to evaluate new candidates.

These checks run regularly, not just at setup. As production systems evolve, they reveal where the simulator has diverged and which components need updating. This continuous validation keeps offline comparisons representative of current production behavior.

Use case 1: Evaluating ranking and relevance tradeoffs with mix-ranking

When ads and organic candidates are ranked together, position affects user engagement, campaign spend, and advertiser outcomes. Organic candidates are non-paid results ranked by relevance, shown in the same placement as ads. Mix-ranking controls this tradeoff by deciding the final order shown to the user.

In this use case, the simulator replays historical requests with both ad and organic candidates available in the same placement context. The main parameter we evaluate, referred to here as alpha, adjusts the balance between ad and organic candidates in the final ordering. By running the same historical traffic across different alpha values, we can compare how the ranking changes before testing any candidate in production.

Illustrative chart of configuration exploration with normalized synthetic axes
Figure 3. Illustrative configuration exploration. Axes are normalized; values are synthetic.

Ad and organic candidates are scored through their respective production scoring paths, which the simulator reproduces. Candidates are evaluated against guardrail criteria with business and engagement outcomes validated in downstream A/B experiments.

The simulator records the ad and organic winner mix by minute and placement, which helps explain whether a candidate improves ranking outcomes through better signal blending or simply by shifting surface area away from organic content. The output is a smaller set of alpha values for live A/B testing. Simulation narrowed the alpha parameter search space to a handful of values that held up across traffic conditions; these became the inputs to a more focused live A/B test, reducing experimentation iteration and increasing the velocity of improvement of our ads ecosystem.

Use case 2: Evaluating sequential decision policies with budget pacing

Budget pacing is a sequential decision problem. A campaign that spends too quickly may exhaust its budget before later opportunities arrive. A campaign that spends too slowly may miss useful demand and finish underdelivered. The pacing policy has to manage this over the full day while preserving advertiser returns and avoiding unnecessary spend degradation.

The baseline pacing policy in production is a Proportional-Integral-Derivative (PID) controller, a standard feedback approach. It modulates how aggressively a campaign competes based on its delivery and how it is tracking against its target over the course of the day. PID controllers are well-suited to auction environments because they react continuously to feedback without requiring a model of the underlying system. In practice, however, they are difficult to tune: the controller exposes several parameters governing how strongly and how quickly it responds to deviations, and the right values are workload dependent. A misconfigured controller can overshoot, oscillate, or converge too slowly to be useful.

We used the simulator to evaluate an alternative based on Primal-Dual Adaptive Pacing (PDAP). PDAP is an optimization-based approach that treats the campaign budget as a constrained resource and continuously adjusts bid pressure to track the target spend curve. In practice, it tracks a single internal pressure signal and translates it into an adjustment on how aggressively the campaign competes, tightening when the campaign runs ahead of plan and loosening when it falls behind. PDAP has fewer free parameters than PID, which makes it a practical candidate to evaluate: if it can match or improve on PID’s tracking behavior, it would reduce the tuning burden without sacrificing control quality.

The simulator lets us compare PID and PDAP under the same historical campaign conditions before either change touches live traffic. For each replay, the simulator advances campaign state over time, applies the active pacing policy, resolves resulting auctions, simulates downstream user response, and records campaign and platform metrics.

Line chart comparing simulator pacing runs against allocation target fulfilment gap
Figure 4. Campaign fulfilment tracking: effect of pacing parameters. Illustrative simulator runs.

Candidates are evaluated on business and engagement outcomes, and filtered by guardrails covering delivery, engagement, and how well it utilizes planned budget targets over the day. The simulator records fine-grained delivery and engagement traces, which makes it easier to inspect why a candidate behaves differently from the PID baseline. To mitigate risk, we filter out candidates exhibiting performance regressions on any guardrail, as well as unrealistic parameter configurations. Given the absence of a production baseline for this bidder, this pre-filtering step is essential to ensure operational stability before live testing. The candidates that remained showed comparable spend tracking to PID with fewer parameters to tune, reducing configuration burden, and moved into a focused live A/B test against the PID baseline.

What we learned

Building the simulator taught us that it needs to be treated as a product, not a one-off analysis tool. A useful simulator needs reliable data preparation, clear configuration, repeatable runs, comparable metrics, and easy ways to inspect results. Without those, teams can run simulations but struggle to trust or act on them.

Fidelity is a moving target. A simulator can reproduce known auction mechanics faithfully and still be wrong when tested in a new regime. Mix-ranking required improvements to how organic candidates are modeled; without accurate organic behavior, the simulated blend between ads and organic results diverged from production. Budget pacing exposed how sensitive the pacing controller is to spend-signal timing. In the simulation, the controller used idealized, timely spend signals, while real-world deployments may involve variations in data freshness and availability. A controller tuned against perfect information can over-correct on stale numbers, and the feedback loop that looks stable offline can drift or spike live. Each new use case is likely to surface a different gap.

The most important lesson is that simulation and live experimentation are complements, not substitutes. Offline replay is fast, repeatable, and safe. Live experiments provide ground truth. When live results diverge from simulated ones, the gap is informative: it points to exactly where the simulator needs to improve. Over time, that feedback loop is what makes the simulator more useful, not just more used. Those lessons shaped what the team focused on next.

Where we are heading

From the start, the goal was not just to replicate auction mechanics, but to build an environment where AI systems can be evaluated, compared, and improved before they touch live traffic. The use cases here, mix-ranking and budget pacing, represent the first layer of that: establishing a reliable baseline for offline evaluation.

The near-term focus is making the simulator easier to use: better tooling for parameter sweeps, clearer observability into why a simulation produced a given result, and support for a wider range of auction modes and pacing strategies.

The next layer is applying this environment to more complex AI systems. A follow-up post covers how we extended the simulator to train and validate generative bidders, where the model does not just react to the current state but proposes future pacing actions. That work builds directly on the evaluation infrastructure described here.

Simulation does not replace live tests. It reduces the candidate space, filters unsafe configurations, and gives live experiments better starting points. The shift is as much about process as it is about technology: moving simulation earlier in the workflow changes how teams approach risk and iteration. The use cases here show that the pattern works. The next step is extending it.


We gratefully acknowledge Allen Lin and Jianning Zhang from Grab’s DNA Data Science team for sharing valuable insights into Grab’s advertising systems and data, and for helping validate the simulator’s fidelity. We also thank Ruike Zhang, Richard Ryu, Padarn George Wilson, and Weilun Wu for their support and guidance throughout this work.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

How a shared merchant data service can degrade gracefully

Post Syndicated from Grab Tech original https://engineering.grab.com/shared-merchant-data-service

Introduction

When a cache becomes unreliable, a shared read service can struggle in ways that spread to the systems that depend on it. We saw this pattern in our merchant data service (MDS). Cache reads began timing out, fallback requests increased database pressure, and service availability degraded.

The trigger was localized; the broader impact came from how each layer responded, passing more work downstream instead of containing the failure.

That amplification follows a predictable pattern, and a few design changes help MDS degrade instead of collapse. The central lesson is simple: a fallback is not a safety net unless its work is bounded.

The merchant data service and its cache

MDS is a shared read service for merchant information. Many client applications use it for questions such as “Is this outlet open?”, “Does this merchant accept orders manually?”, and “What are this merchant’s settings?”. It supports a range of product and operational workflows and handles high-volume, read-heavy traffic. Because merchant data generally changes less frequently than it is read, MDS uses a cache-aside design:

Diagram of the cache-aside read path for the merchant data service
Figure 1. The cache-aside read path. The database is the source of truth; the cache serves most reads.

In normal operation, this works well. The database sees only cache misses, which are a small fraction of traffic. The design depends on one assumption that is rarely written down: that cache failures look like cache misses only occasionally. Without bulkheads, the service is like an undivided ship where a small hull breach (a minor cache glitch) lets water flood unchecked into every compartment, quickly sinking the whole vessel under a sudden wave of database requests it was never built to carry.

Anatomy of a cascading failure

A cache disruption caused reads to time out and fall back to the database. As fallback demand rose, database errors and connection pressure increased; callers then saw more failures, and service availability dropped.

This followed a sequence that the Google SRE book describes as a cascading failure: a local fault triggers a response that increases load, which causes more faults. When cache reads slow or fail, each miss adds database work. As the database slows, callers time out. Retries then add more load to the already degraded path, turning a local cache problem into a feedback loop.

Diagram of how a cache problem can increase downstream load
Figure 2. A cache problem can increase downstream load and widen service degradation.

Recovery took longer because retries and connection pressure kept adding load while the cache and database tiers were constrained. Temporary mitigations reduced symptoms, but the system needed restored headroom and lower incoming pressure before it could recover. Those actions addressed the immediate disruption, not the underlying risk: a cache failure could still send excessive, unprioritized work to shared dependencies.

Short-term client and request-path changes reduced exposure to the immediate trigger. The core vulnerability remained: a dependency failure could still flood shared resources with unbounded, unprioritized work.

The questions the redesign had to answer

The cascade exposed three gaps: cache errors followed the same path as normal misses; fallback work had no firm admission bound; and callers with different business impact competed for shared capacity. Those gaps left the redesign with five questions.

  1. Which requests should survive when capacity is scarce?
  2. How much cache-fallback traffic may reach each database?
  3. How do we stop one workload class from exhausting resources used by another?
  4. Do all clients need real-time data, or can their use cases tolerate a bounded delay in seeing updates?
  5. Can callers use a recently observed value when fresh data is temporarily unavailable?

These five questions point to a clear objective: preserve interactive reads while shedding work that can wait. Our core design principles include:

  • Keep interactive reads available for as long as capacity allows.
  • Shed background and batch work before user-facing work.
  • Bound database work caused by cache failures.
  • Fail fast when a dependency is saturated instead of building an unbounded queue.
  • Serve stale data only on approved read paths with explicit freshness limits.
  • Give on-call engineers scoped controls that do not require a deployment.

Five mechanisms put these principles into practice, starting at the database boundary and working outward to the client application.

Step 1: Know who is calling and how much it matters

Prioritizing work requires knowing a request’s relative impact. Instead of relying on caller-supplied labels, MDS derives a request class from authentication. The table below shows the categorization of incoming traffic by operational criticality.

Class Meaning
P0 (Critical) Interactive reads with direct user impact, such as the consumer app’s API
P1 (Standard) Routine production reads
P2 (Deferrable) Background, batch, and unclassified work that can wait

Clients without an explicit policy receive the lowest-priority class by default. The default stops new or unclassified callers from claiming scarce capacity; promotion requires a reviewed policy change, not a code change. Downstream controls use the same class so the database limiter, circuit breakers, cache connections, and traffic controls make consistent decisions.

Step 2: Put a budget in front of the database

The key change is an admission controller immediately before the database on the cache-fallback path. Each fallback query must acquire capacity from a shared token budget before running. If capacity is unavailable, the request is rejected promptly instead of joining a queue for an already saturated database.

Separate budgets for distinct workload roles. Independent limits protect different database workloads so that pressure in one area does not consume all capacity available to another. The overall budget is coordinated across service instances and managed through runtime configuration.

Cost reflects query shape and priority. Each fallback consumes capacity according to the work it is expected to perform. Lower-priority work carries a higher relative cost than interactive point lookups. The cost relationship is illustrative, not a production setting. The table below displays illustrative token costs. In production, these values are set through runtime configuration.

Query type Base cost P0 total P1 total P2 total
Point lookup by ID 1 1 2 3
Indexed find or range seek 3 3 4 5

Under contention, a more expensive lower-priority query uses its share faster than a point lookup from an interactive caller. Weighting gives higher-impact work a better chance to proceed, but it does not reserve capacity. If interactive demand itself exceeds the shared limit, some interactive requests may be rejected too. A shared weighted budget avoids leaving capacity idle when one class has less demand.

P2 (deferrable) requests do not use the fallback during cache errors. When a cache read fails because of a dependency error, not an ordinary miss or invalid data, the P2 class is rejected before reaching the database limiter. Rejecting P2 early preserves more database budget for interactive and routine work during a broad cache disruption.

Step 3: Bulkheads for connections and failure signals

Admission control limits how much work reaches the database. Bulkheads limit who can starve whom along the way. The name comes from the watertight compartments in a ship’s hull: a breach floods one compartment, not the ship.

Separate cache connection pools by request class. MDS routes requests through independent pools based on their relative impact. Slow background reads can exhaust their own pool without consuming connections needed by interactive traffic. Separate pools help most when slow operations hold connections longer and pool exhaustion could turn slowness into failure.

Separate circuit breakers by request class. Failures in lower-priority traffic do not automatically block interactive work; each class is evaluated against its own observed errors. A shared dependency failure can still affect every class.

Diagram of bulkhead architecture for a shared read service
Figure 3. Bulkhead architecture of a shared read service.

Together, these controls help contain localized cache faults and noisy workloads. Bulkheads reduce interference while capacity remains; they cannot preserve service if the underlying database is unavailable.

Step 4: Give responders a scoped control

Automatic controls address anticipated failure modes, but incidents can reveal new scenarios. A useful response is the ability to reduce traffic from a particular client or workload without waiting for a code release.

MDS supports scoped traffic controls managed through centrally controlled runtime configuration. Rules can target progressively broader scopes. The patterns below are illustrative:

Scope pattern Targeted request group
client:endpoint A particular client and operation
criticality:endpoint A request class accessing a particular operation
criticality: An entire request class

Matching policies can be applied gradually by percentage instead of as an all-or-nothing block. Throttled requests receive a standard unavailable response. Health checks remain exempt so health-based routing can continue. Responders can adjust the scope and level of protection during an incident without a code deployment.

Step 5: Move safe degradation closer to callers

Everything so far protects MDS from load. Callers can also amplify failures: retries and synchronized cache expiry may add pressure while MDS is recovering. Server-side shedding can turn excess traffic away, but a rejected request is still a failed request for the user behind it.

For some relatively stable fields, a recent value may be preferable to an error. More time-sensitive data may require stricter freshness limits or must always be read fresh. The MDS client software development kit (SDK) now includes an opt-in cache that lets approved read paths make this trade explicitly, with a bounded freshness policy.

Every cached value carries its own freshness window. The SDK stores freshness metadata alongside each value, including when it was stored and the boundaries for fresh and approved-stale use. Cache retention covers only that bounded window, while the SDK decides whether the value may be served. Keeping the metadata with the value makes the same policy work across supported cache backends.

Diagram of the SDK reusing known values and serving approved stale data
Figure 4. SDK reuses known values and serves approved stale data.

What the tests and production data showed

Admission control limits database fallback

In controlled load tests, admission control rejected excess fallback work before it reached the database. The limiter kept database work within its configured budget as offered load increased, trading some request success for lower database saturation.

Under heavy offered load in these tests, average database central processing unit (CPU) use was lower with the limiter than without it.

Chart of database load under increasing offered traffic in a controlled test
Figure 5. Database load under increasing offered traffic in a controlled test.

Priority controls shed lower-priority work first

Tests showed that the controls shed work by priority rather than rejecting all callers equally.

Isolated circuits. Lower-priority work gave way first, while interactive reads remained subject to their own limits.

Database admission control. A shared weighted budget can give higher-impact work more opportunity to proceed, but it does not reserve capacity. Interactive requests can still fail when the shared dependency is exhausted.

Chart of priority-based request handling under increasing load
Figure 6. Priority-based request handling under increasing load.

The SDK cache reduced repeated reads

In the read paths that adopted it, client-side caching reduced the number of requests reaching MDS at peak. Reads served from the cache returned faster than those that needed a network call, and caching eased load on the cache tier and the application. When fresh reads were temporarily unavailable, clients could fall back to approved stale values instead of failing.

What we learned

  • Every fallback needs a bound. The cache-to-database fallback was designed as a safety net and behaved like an amplifier. A fallback without a budget spreads failure instead of containing it. The same applies to stale data: it is safe only inside an approved freshness window.
  • Isolation must follow impact, not topology. Physical separation alone was insufficient when callers still shared the same controls. Isolating by workload impact lets the service choose which work is most likely to survive.
  • Latency and queues are failure signals. Incidents can begin with rising latency before visible errors emerge. Timed-out work still consumes capacity, and a retry against a saturated dependency is extra load, not recovery.
  • Test the controls together. Circuit breakers, limiters, retries, cache expiry, and stale serving interact, and failures often come from how they combine. Testing them together under realistic overload reveals interactions that testing one at a time can miss.

What comes next

These controls currently focus on MDS and its client SDK. Looking ahead, we are exploring ways to improve coordination across layers, align admission decisions with current capacity, manage retry budgets end to end, and carry server-validated request priority to downstream dependencies.

Closing thoughts

A shared service cannot make its dependencies infallible. Cache systems can fail, and databases can run out of headroom. What the service controls is how much work it sends toward a failing dependency, whose work goes first, and what callers do when an answer is delayed. By bounding fallback work, isolating callers by impact, rejecting excess demand early, and serving stale data only on approved paths, MDS is better able to contain cache disruptions without turning them into broader service unavailability.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Building the Agent Host Protocol for sessions that continue across devices

Post Syndicated from Connor Peet original https://github.blog/engineering/engineering-principles/building-the-agent-host-protocol-for-sessions-that-continue-across-devices/

Models are now good enough to work for hours or even days on their own. You don’t have to watch over every thing they do, but you still need to be able to check in, no matter where you are. An agent can’t live only inside one application. The work should continue even If you close a window or switch devices.

In GitHub Copilot you can start an agent session in one place and pick it up in another. This session continuity runs on the Agent Host Protocol (AHP), an open standard built first in VS Code and adopted across GitHub. Here’s how it works, what we learned building it, and how you can use it to bring your agents into your own apps and workflows.

Why one integration per client stopped working

GitHub Copilot was first built in VS Code as an extension that bundled its own harness. This gave you access to your agents in VS Code, but it tied their lifetime to the editor. Extensions are attached to a single VS Code window. Close that window, and the agent is gone. Update VS Code, and every agent stops as the application restarts. Connect to a remote machine, and you get an entirely new extension host commit-locked against the version of the VS Code workbench you have.

At the same time, the Copilot app was being developed, alongside the existing GitHub mobile apps for iOS and Android. Each product was doing its own distinct integration with cloud-based agents to work towards delivering session continuity.

Each of these integrations solved the problem for one product, but developers also still want to be able to pull their agents into their own workflows–whether that’s an editor, a terminal, a phone, or a tool they built themselves–and they can’t do that if every client needs its own one-off integration. That’s why developers needed a protocol: a standard, independently versioned language across versions of VS Code, the GitHub Copilot app, mobile apps, and any other client that might host an agent. A shared protocol means every client sees the same agents, history, and state without bespoke integrations, and you aren’t tied to one app’s idea of what an agent session is.

Designing a protocol for agents on every client

The protocol needed to allow multiple clients to interact with the same set of agents seamlessly. Start a session in the cloud from your phone, for example, then continue it from your laptop. It should tolerate network interruptions, reconnections, and concurrent client mutations. And it needed to be full-featured enough for you to do real work from each of your clients.

At the same time, the protocol needed to stay out of agent behavior. Unlike the domains that produced the Language Server Protocol and Debug Adapter Protocol, the world of agents is evolving quickly. That’s why AHP avoids encoding how agents work, and instead focuses on how you want to interact with them.

You also need the protocol to be simple enough to implement on your own client or server. While the full feature set would necessarily be extensive, the core protocol needed to be minimal.

The result of these requirements is the Agent Host Protocol (AHP). It is oriented around URI-identified “channels”, which are the coarsest unit of functionality in the protocol. Every server must implement the root, session, and chat channels, but can also implement more channels that provide terminal support, MCP additions, or OTel reporting, for example.

Within each channel is a reducer-based state object, which drives most of the logic for clients. The server is the arbiter of the state, and each client sends a sequence of actions that either mutate the state or trigger side effects, like sending a chat message. This provides a few very nice properties. Reconnection and replay in poor network conditions are easy: a client sends all queued actions, presents the right ‘loading’ state, and waits for the server to reconcile and acknowledge the actions before confirming them. Clients and servers are straightforward to debug. And reducer-based state also plays nicely with popular UI frameworks like React.

Three clients (VS Code, the Copilot app, and a phone) send dispatchAction messages to an agent host and receive action messages back. Inside the host, required root, session, and chat channels each hold reducer-based state; the chat channel's ordered action log feeds a reducer that produces the next state. Optional terminal, MCP, and telemetry channels sit alongside.

Shipping five clients and two hosts

Adopting the Agent Host Protocol in VS Code required building a new harness and agentic stack underneath it. The Copilot Chat extension, which used to provide all of VS Code’s AI and agentic capabilities, had been growing for over three years, reaching over 400,000 lines of TypeScript, not counting tests. But, as a VS Code extension, it was structured around the lifecycle of a VS Code window and depended entirely on the VS Code extension API. Neither that lifetime nor those APIs would be available in a standalone agent host process.

As we started building the Agent Host Protocol in early 2026, the Copilot SDK was also being developed, and it made sense to leverage it as the foundation for the new agentic stack. This was a big transition. It’s easy to build a harness implementation that says hello and can edit files—we were using the agent host to develop the agent host after the first couple weeks—but it’s another thing to build one that covers the long tail of features developers had come to expect from Copilot Chat.

Line chart of non-test lines of code since 2023. Copilot Chat grows steadily to about 415,000 lines of TypeScript as it moves from microsoft/vscode-copilot to microsoft/vscode-copilot-chat in mid-2025 and into microsoft/vscode in April 2026. Starting in spring 2026, the VS Code agent host grows to about 369,000 lines of TypeScript and the GitHub agent host to about 305,000 lines of Rust.

GitHub has had Copilot cloud agents for a couple of years, allowing developers to run tasks in the cloud from any device. While VS Code was quietly developing the Agent Host Protocol, GitHub was looking to expand that capability to coordinate sessions running on your own devices via the Copilot app, or in cloud sandboxes. This was exactly the N:M problem that AHP was built to solve, so adopting the same technology made perfect sense.

From the outset, the GitHub Agent Host had different requirements than VS Code’s implementation. VS Code runs the host locally and can drop its host on other compute over SSH, containers, WSL, or Dev Tunnels, and it is actually included as part of the VS Code Server bundle. The GitHub Agent Host needed to run in the cloud and across a much wider variety of infrastructure, environments, and security constraints.

Those differing requirements are why they’re separate implementations written in different languages: VS Code’s in TypeScript and GitHub’s in Rust. For now, having two agent hosts has been a good acid-test for the protocol itself. How well does it work when two entirely different teams and sets of agents implement the same protocol independently?

Pretty well, it turns out. Like MCP, the Agent Host Protocol provides escape hatches via custom methods and _metadata on objects that consumers can use for out-of-band signaling. After several months heads-down on our respective implementations, our first task as we worked toward unification was inventorying the ways each implementation had extended the protocol. Many of these extensions reasonably stay GitHub-specific, such as the GitHub Agent Host using metadata to link to project boards. In other cases, variance was a sign of a gap in the protocol; early versions, for example, could not accurately represent shell-type tool output that wasn’t backed by a PTY. And some were bad assumptions, like VS Code’s client assuming a particular structure for the session URIs it received from the agent host. A protocol with only one implementation isn’t truly portable; as we taught our clients and servers to talk to each other, AHP became portable in practice, not just in theory.

A single session, "Fix the flaky login test," runs continuously on an agent host. It is started from the Copilot app at 9:02 AM, a tool call is approved from a phone at 9:40 AM, the diff is reviewed in VS Code at 11:15 AM, and a cloud agent lands the pull request at 11:32 AM.

Today, the Agent Host Protocol provides that same continuity across all VS Code and GitHub surfaces. Agent sessions running locally in the GitHub Copilot app, in cloud sandboxes, and in VS Code all share the same underlying protocol. To see how it’s used, read about how you can work from anywhere with the new connected Copilot cloud experience.

Using the Agent Host Protocol

AHP was designed to be easy to use in clients and servers. Agent Host Protocol libraries are available in Rust, TypeScript, Kotlin, Swift, .NET, and Go, and agents are able to build clients and servers with little prompting. I have a macropad sitting on my desk that reflects my agent’s state in real time, and others have built everything from smart watch apps to Kanban-style task management tools against the protocol. Whether you want a companion app for your own agents, a way to bring agent sessions into your team’s tools, or AHP support in your own editor or agent, the protocol is open for you to build on.

You can connect to an agent host you implement in the Copilot app (enable Experimental > Direct Connections, then go to Environments > Add Agent Host Protocol Host) and in VS Code (via Add Remote Agent Host in the Agents window). You can spawn a standalone version of VS Code’s agent host by running code agent host in your terminal, or see the endpoints for the one in your editor by running code agent endpoints, and samples can help you and your agent get started.

The Agent Host Protocol is an open standard, and questions and suggestions are welcome on GitHub.

Happy coding!

Explore the Agent Host Protocol on GitHub >

The post Building the Agent Host Protocol for sessions that continue across devices appeared first on The GitHub Blog.

Replaying merged changes: how we test whether a knowledge base makes coding agents better

Post Syndicated from Grab Tech original https://engineering.grab.com/replaying-merged-changes-knowledge-base-coding-agents-better

Introduction

Every session, you get a new teammate: a coding agent. It reads code faster than you and has seen more of it than your whole team put together. What it does not have is any memory of how your service got this way.

It can see what the code does. It cannot see why a limit lives in configuration, which nightly job breaks if you touch a shared client, or what an old review thread settled. So it asks, or it guesses.

We built a knowledge base to fill that gap. For each backend service, it maps how requests move through the code, what a change could break, which configuration values the code runs with, and why the team made the calls it did. Agents load it before they touch a service.

The harder part was knowing whether it helped. A plan that reads well can still be wrong, and every agent session starts from scratch, so you cannot watch an agent improve the way you watch a new hire settle in. We found the answer key in our Git history.

Why context is hard to judge

It is easy to keep adding context, and every new file feels like progress. Each one also takes up some of the agent’s attention, can contradict something else it was told, and starts going stale the day it lands. More context can leave an agent worse and more expensive at the same time.

We wanted a number for three reasons:

  1. Opinions do not add up. Ask an engineer or a large language model (LLM) whether a piece of context is useful and you will get an opinion. Ten opinions will not tell you which of ten additions helped.
  2. Public benchmarks measure something else. They test models on public repositories, which the models may have seen in training. Grab Bench tests models and agents on Grab-shaped work. We wanted to hold the model fixed, change only the context, and measure the effect on our own code.
  3. Our knowledge base updates itself. It changes whenever a merge request (MR) lands, and we are adding design documents and discussion threads as sources. Anything that rewrites itself that often needs a check before each update goes live, and a check needs a score.

What the knowledge base holds

For each backend service, an offline build reads the code and writes a set of structured files. Agents pull them in through a skill, a packaged set of instructions they load when a task needs it, and engineers read the same files directly. Any factual claim an agent makes from them has to cite a file and line.

We build it in two passes. The first is plain code analysis with no LLM involved. It parses the service into syntax trees and extracts entry points, imports, configuration keys, and the actual call graph. Only then do LLM sub-agents write summaries and flow documents on top of that structure, and a verifier checks each batch before the build accepts it. The model is describing a call graph we handed it, so it never has to guess one.

Table of knowledge base layers and how agents use each one
Figure 1a. Layers in a service knowledge base and how agents use them.
Diagram of how a service knowledge base is built and kept current
Figure 1b. How a service knowledge base is built and kept current.

Two details matter for the evaluation. The knowledge base lives in Git, so every change to it is a reviewed diff. When MRs merge, an update job rebuilds only the files and flows they touched and opens a knowledge MR for the service owners to approve. Every build also records the commit it indexed, which gives the test a clean cutoff.

The first build indexes the whole service, and later updates rebuild only what changed. We use this approach across a growing number of our backend services.

Every merged change is an exam with an answer key

Every merged MR is a solved problem. Someone wrote it, someone reviewed it, and it shipped. Rewind the repository to the commit just before the merge, give an agent the same request with the solution stripped out, and the merged diff becomes the answer key. Traders do something similar with backtesting. Before trusting a strategy with real money, they run it against history, where every outcome is already known.

Diagram of the replay loop comparing two agents with and without the knowledge base
Figure 2. The replay loop. Both agents start from the same request and the same pre-merge code. Only one line in their prompts differs.

Each run has six steps:

  1. Select. Take recent MRs that changed the service and merged after the knowledge base snapshot.
  2. Scrub the request. Rebuild the request from the MR title and the text that states the need and the expected outcome. Strip file paths, links, code, and anything that describes the solution.
  3. Rewind. Create an isolated Git worktree at the exact pre-merge commit.
  4. Plan twice. Run two identical agents on the same code with the same time budget. Agent A plans from the code alone. Agent B’s prompt has one extra line that turns on the knowledge base skill.
  5. Grade. An LLM grader scores each plan against the merged diff on a fixed rubric.
  6. Pair. Compare the two scores for each MR, then aggregate across the set.
for mr in select_mrs(service, merged_after=kb_snapshot_date):
    ask = scrub(mr.title, mr.description)        # need and outcome only
    repo = worktree_at(mr.parent_commit)         # the code as it was before the merge
    answer_key = mr.diff                         # never shown to the agents

    plan_a = agent.plan(ask, repo)                             # code only
    plan_b = agent.plan(ask, repo, skills=[knowledge_base])    # the only difference

    for variant, plan in (("a", plan_a), ("b", plan_b)):
        record(mr, variant, grader.score(plan, answer_key, rubric))

report(paired_means(), better_tied_worse(), largest_movers())

The following is illustrative pseudocode. The function and variable names are simplified.

The agents write a plan, not code. A plan lists which files to change and how, the risks, how to verify the change, and how confident the agent is. We stopped at the plan on purpose. Writing a change takes two skills: working out what it needs, and then writing it correctly. The knowledge base is there to help with the first, and a plan shows that part directly, without the model’s coding ability moving the score. Code has many right answers, and two correct implementations rarely match line for line, so diffing an agent’s code against the merged code would penalise valid alternatives. Plans are also quick to produce, so we can rerun a full 50-MR sweep with both variants whenever something changes.

A good plan still is not working code. It can be implemented badly, and some mistakes only show up when the code runs. We have also run the replay with agents writing code, but the results here cover plans only.

Making the test fair

It is easy to build a replay test that looks fine and measures nothing. Five decisions keep ours honest.

Grade against what shipped

Plans do not come with tests, so an LLM grades them, and LLM graders are easy to impress. A fluent, confident plan can score well while missing the point entirely. Our grader always has the merged diff in front of it, and every point it gives has to trace back to that diff. A plan that sounds right but misses what shipped scores low.

Keep the answer out of the exam

A test like this fails quietly when the answer leaks in. We close four paths:

  • Through the knowledge base. A knowledge base built after an MR merged may already describe that change. We only replay MRs that merged after the snapshot, so the knowledge always predates the answer.
  • Through the request. MR descriptions often spell out the solution. The scrubber keeps the need and the expected outcome, and strips file paths, links, code, function names, and sections like “implementation” or “changes made”. If nothing usable is left, a separate LLM call rewrites the request with one rule: describe the need and the outcome, never the approach.
  • Through the repository. Agents work in a worktree at the pre-merge commit and are told not to look up the MR, its diff, or later history. The answer keys live outside the worktree.
  • Through the grader. Each grader sees one plan and the diff. It never sees the other variant’s plan, so it cannot grade on a curve.

Here is what the scrub does to a made-up MR:

Example of scrubbing an MR request before and after
Table 1. Example scrub of a made-up MR request. Illustrative only.

Choose changes worth planning

Some MRs have nothing to plan, and a set full of them drifts towards ties. The selector skips reverts, dependency bumps, test-only changes, file moves, MRs that mostly touch code outside the service, and single-file changes under about 15 lines. What is left is work an engineer would have to think through.

Use a rubric a reviewer would recognise

Each plan can earn up to 8 points across five dimensions, based on what a human reviewer checks:

Rubric dimensions and maximum points for grading plans
Table 2. Rubric dimensions and maximum points.

Three rules shape the scores:

  • Every point traces to the diff. Confidence on its own earns nothing.
  • Open decisions are capped. The failure we saw most often was an agent handing a core decision back to a human. A plan that does that scores at most 1 on each of the first two dimensions.
  • Scoring is award-only. Correct extra scope costs nothing, and wrong scope earns nothing.

The grader explains every score with references to the plan and the diff, and we read the biggest score changes and the edge cases ourselves.

Change one thing, then repeat

The two agent prompts differ by a single line. The MR, the code, the request, the time budget, the grader, and the rubric all stay the same, so any change in score comes from the knowledge base.

The same setup works for other comparisons. Swap the model or the agent harness instead, and the same MRs and grader measure that. Our first sweep ran five agent stacks from three model providers, each with and without the knowledge base, so the scores also compare across stacks.

Agents are probabilistic, so a single run is just one sample. We average repeat runs for each MR and variant before pairing them. Timeouts and missing plans are reported separately and never count as zero.

One change, two plans

Here is how the two plans differed on the made-up refund request. The details are invented, but the pattern is the one we saw most. Without the knowledge base, the agent hands settled questions back to the reviewer. With it, the agent answers them and says where each answer came from.

Side-by-side comparison of plans with and without the knowledge base
Table 3. Side-by-side plans for a made-up refund request. Illustrative only.

That is a reason the code cannot give. A decision record, distilled from earlier MRs, explains why limits live in configuration: on-call engineers can raise them during an incident without a deploy. The code shows where the limit is read. Only the record says why, and the plan cited it.

What we found

We replayed 50 recent MRs from a large, actively developed backend service, across five agent stacks from three model providers.

Planning performance improved across the board, with knowledge quality outweighing model tier. With the knowledge base, every stack beat the strongest stack without it, including the budget-tier and previous-generation models. Stronger baselines gained less. If you are choosing between a bigger model and better context, it comes down to cost.

Bar chart of average plan scores with and without the knowledge base across agent stacks
Figure 3. Average plan score out of 8 for each agent stack, with and without the knowledge base, across 50 MRs.

Most of the gain came from knowledge built from the code. On one stack, we added the layers one at a time. Flow documents, impact maps, and live configuration values delivered most of the lift, and decisions, glossary, and conventions added the rest. Flow documents and impact maps contain nothing the code does not already say. What they save is the searching and guessing the agent would otherwise repeat on every task, along with the variance that comes with it.

If you build one thing, start with flow documents and impact maps. They come straight from the code, so you can compute and check them, and they carried most of the lift in our runs. Add decisions and conventions once updates from merged MRs are flowing.

Most plans improved, and the weakest improved most. On the stack we ran most often, the knowledge base made plans better on more than half the MRs and tied on almost all the rest. The number of plans with full marks nearly tripled. The weakest quarter went from about half marks to about three quarters.

Chart of average score per rubric dimension with and without the knowledge base
Figure 4. Average score per rubric dimension as a share of its maximum, with and without the knowledge base, across 50 MRs on one agent stack.

The biggest jumps were in “Found the right code”, “Understood the intent”, and “Was honest about uncertainty”, each up by more than a fifth of its range. With knowledge, agents found the code the change needed, understood why it changed, and only claimed confidence they could back up. “Saw the risks” and “Planned verification” were already at or near full marks, so there was little room to move.

Every knowledge update takes the same exam

The replay also protects the knowledge base itself. When it changes in a big way, such as a new source, a new format, or auto-learned context, we replay the same MRs against the current version and the updated one. If the score holds, the update ships. If it drops, the update waits, and its owner gets the list of MRs that got worse. Routine updates from merged MRs keep flowing as usual.

A weaker update gets caught here, before any agent plans with it. We hold knowledge to the same bar as code: it has to pass its tests.

Diagram of the knowledge update gate using replay scores
Figure 5. The knowledge update gate. A material update replays the same MRs, and the score decides whether it ships.

What we learned

  • The use case picks the evaluation. MR planning comes with an answer key in every merged change, so that is what we evaluated. Other kinds of knowledge will need answer keys of their own.
  • Known structure beats guessed structure. Let LLMs describe structure, not discover it. In our experiments agents did better when they searched a link graph we built from the code than one whose links an LLM had guessed. Chunked similarity search also had trouble working out the order of events and which information was current.

What comes next

The replay idea works for any finished piece of work with a recorded outcome, like a resolved incident or an answered metrics question. We are building a shared knowledge layer across engineering, analytics, data science, and product, and each part will have to earn its place the same way.

Conclusion

A service’s merge history is a record of solved problems with the solutions attached. Replaying it turned our knowledge base from something we believed in into something we can measure, and every major update now has to pass the same test before it ships. If you are building context for coding agents, you can start the same way: pick 50 merged changes, rewind, and grade the plans against what shipped.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Inside GitHub’s new Git storage architecture

Post Syndicated from Karthik Raman original https://github.blog/engineering/architecture-optimization/inside-githubs-new-git-storage-architecture/

Last week at GitHub Universe, we announced our new Git storage architecture, capable of handling thousands of writes per second with reads that scale on demand. Through internal testing, we’ve demonstrated the ability to support 5,000 concurrent agents working on a repository, sending 7,200 pushes per second to a repo, all while serving read traffic with consistently low latency. This new architecture is the foundation for GitHub to support agentic development for hundreds of millions of developers, and we’ve been building it underneath GitHub while it keeps running.

Over the past year, agents changed what a busy repository looks like on GitHub. In our first post in this series, we laid out the two principles behind our next-generation Git storage architecture: minimize coordination, and decouple storage from compute. In our last post, we covered the bridge: moving 99.99999% of repositories into Azure, scoping the write quorum to individual references, and standing up virtual replicas backed by Azure Blob Storage.

We also left off with an observation: very little of a write needs to be ordered. Git objects are immutable and named by their contents, meaning two writers can store them at the same time without agreeing on anything. The part of a push that needs agreement is the reference update, and a reference update is tiny in comparison. Virtual replicas were the first step toward building around that, and the means by which we onboard repositories to the new architecture.

The rest of the architecture builds on that observation. Only reference updates need agreement. That lets the parts of Git infrastructure that used to be tightly coupled (storing data, serving requests, and maintaining repositories) scale independently. For developers, Git stays Git: they push, fetch, and branch the same way, with the same protections in place. Below, we walk through the requirements behind the design, follow a request through the system, and dive deep into two of its components.

Building for agent scale

We think about the scale of the GitHub platform along two axes:

  1. Horizontal scale is how many developers and agents can work across many repositories. Many of GitHub’s current approaches on this axis have been battle-tested over the years and are carried forward to the new architecture: partitioning of tenants across infrastructure, isolation and/or fairness enforcement of tenant traffic, and load-aware routing, to name a few.
  2. Vertical scale is how many developers and agents can work on one repository. As agents write more code, we expect individual repositories to get larger and busier, so most of our requirements came from the vertical axis.

Today, the busiest repositories on GitHub.com receive at most dozens of writes in a single second, typically in short bursts. As more of that work shifts to agents running in parallel and around the clock, we expect those bursts to become a sustained rate within the next year. Each push leads to more reads: CI runs, deployment systems pull the new commit, and other agents fetch it for context. This read fan-out results in a large amplification effect on overall traffic that scales with writes.

We’re already seeing this trend play out on repositories at the top of the curve. The chart below shows daily requests to one repository on GitHub from March to May, when its traffic grew about 4x. Its growth has continued on an exponential trajectory since then.

Line chart of daily requests to a single repository from March through May 2026. The March average is 44M requests per day and the May average is 181M requests per day, about a 4x increase.

We have to plan for a world where agent-driven development keeps accelerating at this speed. Instead of planning for the next increment, we set a target of at least two orders of magnitude more scale. For a single repository, that meant the new architecture needed to:

  • Accept thousands of writes per second.
  • Support multiple writer nodes. There are two reasons for this:
    • Experience has taught us that indexing incoming packs and checking object connectivity are the most CPU-expensive parts of a write, and that cost scales with the size of the write, so a single node will become compute-bound quickly.
    • Spreading that work across many nodes improves fault tolerance and shortens recovery when a node fails.
  • Minimize commit latency. An agent waits on each push before it moves to its next step.
  • Record changes in order for each reference with the ability to quickly linearize across references. A virtual replica that falls behind needs to catch up by downloading only the data it needs to serve the incoming request.
  • Keep reads cheap when nothing has changed, which is the common case given the read-to-write ratio.
  • Let each component scale independently.

On top of that, the system had to be able to improve overall reliability and scale globally.

Introducing “Project Rubicon”

In May of 2026, hot on the heels of the initial Azure migration, we started working on a design that could meet those demands. We tried several approaches. In all of them, pack data lived in Azure Blob Storage, and in some we experimented with keeping reference state there too. We’ll cover some of the trade-offs we found below, but we settled on a design we felt maximized throughput while preserving the correctness, durability, availability, and latency guarantees a platform like GitHub requires. We called it “Rubicon,” a nod to the point of no return the industry crossed with agentic development.

Let’s walk through Rubicon from the top down. Many things stay the same: requests from Git clients, the API, and the web UI arrive at Spokes, which still handles routing and load balancing, and serves the internal API that the rest of GitHub uses to read and write repository data. Spokes also maintains its role as a placement and balancing service, maintaining the partitioning, isolation, and tenant fairness required for horizontal scale. The data plane underneath Spokes, in contrast, is new.

Architecture diagram. Git, API, and Web requests pass through Spokes to groups of virtual replicas per repository. Virtual replicas hold only cached state. Ref-CAS stores refs and the pack manifest, and Azure Blob Storage stores pack data. Compaction nodes compact and garbage collect packs in Blob Storage and update the pack manifest in Ref-CAS.

Spokes routes each request to one of a small group of virtual replicas assigned to that repository. Virtual replicas are a single fleet of disposable compute that serves reads, writes, or both. A virtual replica’s local disk is a cache that can be rebuilt at any time.

Spokes routes a repository’s traffic to the same virtual replicas when it can, which keeps their caches warm and latency low, but nothing about correctness depends on a request landing on any particular virtual replica. When a virtual replica goes away, the repository’s other virtual replicas keep serving, and a replacement fills its cache as traffic arrives.

When a repository gets busy, we add more virtual replicas. Separately, a fleet of compaction nodes works in the background, directly against Blob Storage and Ref-CAS, to merge each repository’s packs and remove unreachable objects. That work never runs on a virtual replica, meaning their CPU and memory can be almost entirely dedicated to serving requests.

Durable state lives in two places:

  1. Git objects, in the form of packs and auxiliary read acceleration data, live in Azure Blob Storage.
  2. References and the list of packs that make up the repository (the pack manifest) live in a separate replicated log service we call Ref-CAS (for “Reference Compare-and-Swap”).

Let’s walk the architecture from the perspective of a write and a read:

  • Write: a virtual replica indexes the incoming pack and uploads it to Blob Storage, then commits one transaction to Ref-CAS that lists the pack in the manifest and updates the references. Later, a compaction node merges that pack with others to keep reads fast.
  • Read: a virtual replica checks its reference version with Ref-CAS, pulls the packs it needs from Blob Storage into its cache, and serves the read from there.

There are many distinct approaches we’ve taken within the new architecture, from the software stack on the virtual replicas to how traffic routing and workload scheduling are tuned for different use cases (e.g., many small repos vs. one large one). Let’s dive deep into two components of the architecture and tell their stories centered on the two design principles.

Minimizing coordination: mutating reference state at high throughput

Object storage services like Azure Blob Storage are incredibly good at what they do, and natural fits for many data-heavy applications like source code storage. They are durable and replicated, hold as much as we need them to, have a relatively low cost per byte, and deliver exceptionally high aggregate throughput so long as traffic is spread across many keys. As a result, nearly everything durable in the new Git storage architecture lives in Azure Blob Storage, including:

  • Packs and indexes written by pushes, compaction, and garbage collection.
  • Various read accelerators (like multi-pack indexes, reachability bitmaps, and some custom formats) that our maintenance process builds from those packs.
  • Records that let compaction and garbage collection resume or audit their work, along with the leases that compaction nodes use to claim work.
  • Cached responses for frequently repeated fetches.
  • Checkpoints for the reference state of the repository, though not the authoritative state used to serve requests.
Diagram of one repository's data in Azure Blob Storage. Push, Compaction, Maintenance, GC, and Ref-CAS write into it, and fetches read from it by exact key. It holds packs and indexes, records and leases, read accelerators such as the multi-pack index and reachability bitmap, cached fetch responses, and reference checkpoints.

Most of that data is written once to a distinct key and never changes afterward, which is what makes it highly suitable for Blob Storage.

References are the opposite. A busy repository’s references are a relatively small piece of state that many writes race to update at the same time. That access pattern is harder to serve from Blob Storage, and our first prototypes showed us why. Object storage for this kind of workload is an intuitive choice, and one that works well up to a certain level of scale: conditional writes give a compare-and-swap for free, and the data is already durable and replicated. However, we ran into a difficult set of choices, illustrated below by two approaches we tried.

Our first approach was a write-ahead log for all of a repository’s references, indexed by a single blob. Every update is a conditional write against that blob. It’s correct, and reads are cheap: a virtual replica asks whether the blob has changed, and if it hasn’t, it’s done. Writes are where it falls short. Only one conditional write to a blob can be in flight at a time, so even when we batch every push that arrives during a write into the next one, the repository’s write ceiling is one write per round trip to a single blob. In practice, this netted us write throughput in the mid-hundreds per second.

Our second approach split the references across several segment blobs, with each reference hashing to one of them. Writes to references in different segments no longer wait on each other, which raises the ceiling. But a read now has to check every segment to know whether anything changed, and it’s only as fast as the slowest segment. We’d traded write latency for read latency, and reads outnumber writes by orders of magnitude. We can visualize this by showing multiple writes and a read side by side:

Neither option met every requirement, so we built something else: a replicated log service dedicated to references, or the Ref-CAS service. This is the (small) consensus group we said at the end of the last post was still somewhere in the stack. Here’s how it works.

Each reference update in Ref-CAS is a compare-and-swap committed by a quorum. A transaction locks only the references it touches, checks that each one still has the value the writer expects, and becomes visible once a majority of the log’s replicas have recorded it. Agents mostly push to their own branches, so most updates don’t contend, and they replicate in parallel. When two pushes do update the same reference, only one will append to the log.

Each commit to Ref-CAS gets a log sequence number (LSN), and the repository’s version is the LSN of its latest commit. Reads start with a version check against that version. A virtual replica sends the version of the reference state it already holds. If that version is still current, the reply carries no references at all, and an unchanged repository costs a single comparison. If the virtual replica is behind, it gets back the current references and version, along with pointers to pack data and anything else that needs to be known, such as when the last garbage collection cycle occurred.

Unlike the consensus group in our legacy architecture, Ref-CAS never holds or validates object data. It only stores pointers to it. A virtual replica uploads a push’s pack to Blob Storage before it commits the reference transaction. A reference only ever points at objects that are already durable.

These approaches allow us to transact reference state alone in the tens of thousands of operations per second, and provide a baseline for additional annotations on the replication log that help reads decide what to download for a given request.

But supporting thousands of writes per second on a single repository creates a second-order problem: maintaining the performance of reads and writes. For that, we needed a different approach to compaction.

Decoupling storage from compute: compaction at thousands of writes per second

Every push adds a pack to Blob Storage. Git can serve a repository from many packs, but each additional pack makes lookups slightly more expensive, so the pack count can’t grow without bound. In our legacy architecture, compaction runs on the same replicas that serve traffic, and it has to run on every replica. In the new architecture, it runs entirely in the background on separate nodes, directly against durable storage, using the Ref-CAS service to notify virtual replicas of the evolving state.

Compaction nodes each claim ownership over a subset of the repository’s data via a lease, which allows us to scale compaction horizontally. Here’s how one compaction node works through a single shard of a repository’s packs:

The node first takes a lease on the shard in Blob Storage, so only one node compacts a shard at a time. Meanwhile, virtual replicas keep uploading packs and listing them in the pack manifest. The node reads the manifest to find new packs and collects them into an open segment, which is effectively a holding ground for data about to be compacted. When the segment reaches a defined limit based on pack count, size, or age, it seals the segment so it accepts no new packs, then combines its packs into fewer, larger ones. While compaction happens, the next segment for the shard can begin capturing its input packs. Before anything is published, the node checks that the new packs contain exactly the same objects as the inputs. It then uploads the new packs and adds them to the manifest. A second transaction removes the inputs from the manifest, and cleanup deletes them later.

To scale out, this process runs independently for many shards at once. Each pack’s hash maps to a shard, so adding shards and nodes adds compaction throughput. A compacted pack that’s still under the size limit goes back into a shard by its own hash and merges again, so packs grow in tiers until they reach the limit. The net result is an effectively flat pack count while pushes climb:

Compaction merges packs, but it keeps every object. Garbage collection is the step that removes objects nothing references anymore, like the ones left behind by deleted branches and force-pushes. In our new architecture, garbage collection works very similarly to compaction by using dedicated workers to handle the compute-heavy portion. It also has a few special behaviors for safely removing data, which are worthy of their own discussion.

Using these approaches, we’ve been able to consistently demonstrate a flat latency curve as writes climb, and we have other planned optimizations to make the compaction and garbage collection processes themselves more performant.

What comes next

The two principles we started with let each part of this architecture scale on its own. We scale reads and writes by adding virtual replicas. Ref-CAS orders each reference independently instead of the whole repository. We scale maintenance by adding compaction nodes. Our goal is for every repository, from one developer’s side project to the busiest monorepo, to run on the same architecture with no special handling for the busy ones. Repositories don’t stay small. A side project can pick up a fleet of agents overnight, and it shouldn’t need a migration or special handling from us to keep up. One architecture also means every improvement we make reaches every repository at once.

This foundation lets us do a lot more. We’re focused on three areas next: scaling the architecture beyond what we can predict we’ll need today, making agents more efficient at the work they do on GitHub, and evolving Git itself for agentic development.

Improving the architecture

We have plans to take this architecture further. Each of these improvements lets a repository handle more activity while reducing the work behind each request:

  • Read only what’s needed. Fetch a single object from Blob Storage instead of the whole pack that holds it.
  • Organize packs by type. Group commits, trees, and blobs into their own packs. Many requests then touch less data.
  • Partial replicas. Serve requests without every pack on local disk.
  • Materialized views. Keep repository data in ready-to-use forms, like prepared archives, a near-live shallow copy of the default branch, and agent session context stored alongside each commit.
  • Global replicas. Place replicas in any region, close to the workloads that use them. Reads stay within bounded staleness of the latest write.
  • Scale to zero. Grow and shrink the fleet with the repositories that are actually active.

Efficient agent operations on GitHub

Scaling the infrastructure is one side of supporting agents. The other side is making each agent operation cheaper: fewer bytes to fetch, fewer round trips, and less waiting on changes. Each of these fast-follow items builds on the storage work in this post:

  • Work without a clone. Many agent tasks never need a full working tree. They need a handful of files and enough context to make a change. They can read both straight from the server.
  • Atomic commit API. Land a multi-file change in one operation. The whole change commits, or it’s rejected cleanly on conflict.
  • Event streams. Agents and the systems around them work best with real-time information. A generic event stream lets them subscribe to changes and react as they happen.

Improving Git for agents

We also have work to do in Git itself. GitHub has been a longtime contributor to the Git project, and we’re not stopping now. A few examples of the work we’re excited to continue:

  • Lightweight clones. Partial clone, shallow clone, and sparse checkout each let an agent fetch less. Each one has gaps. They don’t always work well together, either. We want to improve each piece and make them fit.
  • Remove hidden scaling costs. Git still has code paths that slow down much faster than the repository grows. Recent releases fixed several of them, but we expect to find more.
  • Faster history walks. Metadata like the commit-graph can answer merge-base and reachability questions without walking every commit. That matters most when an agent’s API call turns into Git work on the server.
  • Avoid common gotchas. Agents make the same mistakes developers do. Git can catch more of the common ones and warn before they cause damage.

Agents have changed how software gets built. GitHub and Git are changing with it. We’re excited to take this new architecture across the starting line. It’s available in a limited private preview now, with a broader rollout early next year. We can’t wait to see what teams build when the number of agents working on a repository is limited by their ideas. We’ll keep evolving Git and GitHub alongside our customers and the Git community.

The post Inside GitHub’s new Git storage architecture appeared first on The GitHub Blog.

How Grab built Scarlet: the AI teammate that turns a Slack message into a production data pipeline

Post Syndicated from Grab Tech original https://engineering.grab.com/how-grab-built-scarlet-blog-draft

Introduction

In the blog From firefighting to building, we described the agents our Analytics Data Warehouse (ADW) team built to take routine work off data engineers. Scarlet was the Enhancement Agent in that post. It read a ticket, wrote the change, and opened a merge request (MR) for an engineer to review. A routine enhancement dropped from about a day to one or two hours.

Figure 1. A pipeline change without Scarlet.

Then other teams asked for it, and four limits became clear:

  • One team only: Scarlet’s repository and conventions lived in a single system prompt sent on every request. A second team meant forking the bot.
  • No proof the data was right: Scarlet could run a change in a test environment, but nothing checked whether the output data was correct. That hour of manual validation still fell to a person, and it was the step most often skipped.
  • Shared access: Early versions of Scarlet did not tie each action to the permissions of the person who requested it.
  • Slack only: Every request needed someone to type it into a thread.

This post is about closing those gaps. We rebuilt Scarlet around a short core prompt and a library of skills: Markdown documents, one per capability or per team, loaded only when a request needs them. The prompt shrank about 25 times, and teams now review that knowledge like code. Scarlet also tests the data its changes produce, runs under the asker’s own permissions, and takes work from Jira tickets and other agents.

Since this version reached production in May 2026, the repositories Scarlet ships to have grown about four times, weekly usage has roughly tripled, and the merge rate has climbed from about half to more than four in five. The merge still belongs to a person.

What Scarlet does

To recap our initial blog: an engineer pastes a ticket into a Slack thread, Scarlet finds the repository and pipeline, checks the catalog, writes the change, and opens an MR for a human to review. That loop has not changed. Neither has the boundary: Scarlet has no merge or approve call, so merging stays with people.

Everything around that loop has changed.

In the thread:

  • A plain-language description is enough. No ticket needed.
  • Scarlet posts a plan before it touches a file.
  • A live plan card shows each tool call as in progress, complete, or failed, with a cancel button.
  • Follow-ups keep the earlier context, so “add one more column” needs no repetition.
  • Attached files load as reference material, never as instructions.

In the MR: a structured description, a bot label, and the requester tagged and assigned. If the branch already has an open MR, Scarlet updates it instead of opening another.

Figure 2. Scarlet’s live plan card during a pipeline build.

Scarlet now also works with the data catalog and the data quality platform, and handles far more scheduler actions than before. On each of them it follows one rule: show what it is about to do, then wait for a yes.

  • Catalog and data quality changes: Scarlet posts the exact update it will write and waits for approval.
  • Scheduler actions: Scarlet spells out which host, which directed acyclic graph (DAG), which run, and what it will do, then waits for approval.
  • Read-only requests: no approval needed.
  • Data contracts: Scarlet will not create one for a table whose quality checks are failing. A data contract tells downstream users the table is safe to depend on, and a table with failing checks is not.

Scarlet also answers questions about the data, such as how many rows landed yesterday. It runs those queries as the person asking and returns only aggregates, never per-person rows, under a hard cap that holds even if the model ignores its instructions.

How the agent plans and acts

A request passes through four layers:

  1. Slack carries the conversation and progress updates.
  2. A reasoning loop picks the next action.
  3. The skill library supplies the instructions for the current team and workflow.
  4. An action layer reaches Jira, GitLab, Airflow, Google Docs and Sheets, and our internal data platforms.
Figure 3. How a Slack message becomes a merge request.

The first post described streamlining more than thirty verbose tool descriptions. Scarlet now goes further. Each internal platform sits behind a Model Context Protocol (MCP) bridge with two tools, one to list operations and one to call them, and schemas load only when needed. A platform with dozens of operations adds nothing to a request that never touches it.

Scarlet has two identities, split by what it touches:

  • Data platforms (catalog, data quality, jobs, scheduler): Scarlet has no credentials of its own. Each operation runs as the requesting user through a short-lived token from their sign-in, so anything they cannot touch fails for Scarlet too.
  • Source control: operations run as the Scarlet bot, so a machine-authored MR is easy to spot.

When a user asked how its access worked, Scarlet summed it up: “I can only do what you can do. I’m an accelerator for your own permissions, not a bypass around them.”

Every reply ends with a footer linking to its full trace, so a reviewer can see exactly what Scarlet did and why.

The skill library

Scarlet’s core prompt contains no workflow detail. It tells the model to load the relevant skills before acting. Skills describe how to do the work, and tools do it.

Each skill is a Markdown document that defines one capability or one team’s conventions, plus the skills it depends on. The table certification skill, for example, pulls in the catalog and data quality skills it relies on.

The library has four kinds of skill:

  • Platform skills cover common operations, such as reading tickets, finding tables, and opening MRs.
  • Routing skills work out which team and repository a request belongs to.
  • Repository skills record a team’s repository, schema ownership, scheduler, labels, and conventions.
  • Workflow skills run end-to-end tasks: building pipelines, rewiring sources, certifying tables, validating data changes, and reviewing MRs.
Figure 4. Skill resolution.

A skill goes through the same life cycle as code:

  1. An author writes or changes a skill and opens an MR. Scarlet can draft this MR itself.
  2. Reviewers approve it the way they review code.
  3. A pipeline validates the skill and publishes an immutable bundle.
  4. At startup, Scarlet activates one bundle version and writes that version into its prompt, so every answer traces back to the exact instructions that produced it.

A new team joins by adding one repository skill. The library has roughly tripled since July. Much of that growth is team skills, and several of them were written by the teams that use them.

Validating the data

Continuous integration (CI) proves that the code runs. It cannot prove that the data is right: a join that silently drops rows, a column that is suddenly half null, or a swap that overwrites yesterday’s output all pass CI. Manual checks were easy to deprioritize, because they take longer and typically require familiarity with both Structured Query Language (SQL) and the tables involved.

Scarlet now tests the data as part of the change. This job used to belong to a separate validation bot, and we folded it into Scarlet. The flow:

  1. During CI, our data platform runs the candidate change in an isolated environment and publishes a manifest linking the commit to the table it produced.
  2. Scarlet reads the manifest, so it has real candidate output before anyone reviews the MR.
  3. From the change, Scarlet works out what to compare: the target table, the changed columns, and the table’s keys and partitions.
  4. It runs its checks against the current production table.
  5. It posts a verdict of pass, fail, or inconclusive, with evidence for every check, bound to the exact commit it tested.

The checks:

  • Schema and type differences.
  • Row counts.
  • Duplicates and key reconciliation.
  • Null rates and column profiles.
  • Numeric statistics such as minimum, maximum, mean, and spread.
  • Row-level differences between the two outputs.

The rules:

  • The kind of change sets the mandatory checks, and requesters can add their own scenarios in the ticket.
  • Inconclusive counts as a failure.
  • If the change moves after testing, the verdict expires and the checks run again.

Automated checks can make MR validation and table comparisons less time-consuming than manual review.

We are extending the same flow past the merge. Scarlet will watch the first production run after an MR merges, rerun its checks against the live output, and, if they fail, raise a revert MR for a human to approve.

Figure 5. Testing a change’s data.

Beyond Slack

Not every request starts with a Slack message anymore. There are three ways in:

  • Slack thread: the flow described above.
  • Jira label: within about five minutes of a ticket being labeled for Scarlet, it picks the ticket up, starts a thread in its channel, tags the assignee, and works the ticket through to the MR.
  • Command line and run application programming interface (API): engineers use Scarlet from a terminal, and coding assistants such as Codex and Cursor call it as a tool. The agent, its skills, and every credential stay on the server, and sign-in pauses work as they do in Slack.

Seeing it in action

The first post walked through a single column change for our own team. These three cases show new kinds of work and new teams.

Our own first pipelines

  • Ask: onboard a new finance source system into the data lake, which needed many similar pipelines. An engineer described the task in a single message.
  • What Scarlet did: read the source schema from the catalog, generated the transformation, DAG, and dependency files, and opened an MR within 30 seconds of the go-ahead. CI passed about five minutes later.
  • Result: every pipeline that week passed CI on the first attempt, and almost all of the generated code shipped without rework. We estimate the work took around 6% of the engineer time it would have taken by hand.

The first merge request outside our team

  • Ask: an analytics engineer on a commerce team, in their first week with Scarlet, wanted five fields added to a clickstream table.
  • What Scarlet did: opened the MR, then its own review pass flagged that the field names broke the upstream team’s convention. The engineer picked the convention, and Scarlet updated the MR and the ticket.
  • Result: a reviewer merged it the next day.

A team onboarded mid-request

  • Ask: an engineer on a lending analytics team, using Scarlet for the first time, wanted a scheduled job changed for a team Scarlet had never been set up for.
  • What Scarlet did: when the engineer typed “onboard my team to Scarlet”, it drafted the team’s skill as an MR. After a single sign-in, it updated the job under the engineer’s identity and ran its post-change checks.
  • Result: the skill MR merged the next day, and the job change went through under the engineer’s own permissions.

Lessons from production

Templates for predictable structure

What happened: during one migration, Scarlet produced a large MR that passed CI and failed at runtime. The model had guessed part of the job configuration.

What we changed:

  • Deterministic scaffolds for predictable structures. They run the platform’s own code generator and validate the output against a contract.
  • A Slack wizard for teams that prefer forms. It never calls the model and captures all the necessary details as required.
  • A validate, lint, fix loop for generated SQL and configuration. It stops after a few failed attempts and asks a human.
  • The model keeps only the work that needs judgment: mapping columns, writing transformations, explaining failures.

Sign-in as a pause

What happened: when Scarlet acts as the user, some platforms need that user to sign in first. At first, hitting one of those mid-run ended the workflow, and replaying the request lost the progress.

What we changed: sign-in is now a pause. The run checkpoints at a LangGraph interrupt, and the sign-in callback resumes it from that point while the same plan card keeps updating.

Measuring without reading conversations

What happened: the first post’s feedback loop ran on reviewers rating each answer in Slack. Scarlet’s output is an MR reviewed in GitLab, so that loop did not carry over, and after launch we could not say who used Scarlet, for what, or how often it succeeded.

What we changed: a recorder that captures metadata from the tool stream (requester, source, skills, tools, duration, outcome, intent) without storing conversations. Request text is opt-in, and anything that looks like a credential is redacted. The figures below come from it.

Impact

These figures come from the usage events Scarlet records.

Figure 6. Weekly usage and merge rate, May to September 2026.
  • Weekly usage held steady from July to mid-August, then climbed. In the week of 7 September it reached about three times the usual request volume from about twice as many users, and the following week held near twice the usual level.
  • The share of monthly users who came back for a second week rose from about 42% in July to 56% in August and stayed above 50% in September. The top user’s share fell from nearly half of all requests to under 10%.
  • Repositories with a Scarlet MR grew about fourfold from May to September, and monthly MRs opened grew more than fourfold from June to September. The merge rate rose from about 50% in May to over 85% in September. Early September alone produced more merged code than the whole of August.

The mix of requests changed as the skill library grew:

  • Table discovery grew fastest, more than six times from July to September, as new teams explored the catalog before asking for changes.
  • By September about half of all requests were questions about the data, not changes. Answering under the asker’s own permissions turned out to matter as much as the merge boundary.

Current limits

  • Long threads degrade answer quality, and a very large request can exceed a single model turn. Starting a new thread helps once older context stops being useful.
  • Coverage gaps: schema and freshness checks only, certification for production tables only, and source rewires stop for a human when fewer than about 70% of columns can be mapped.
  • Data testing covers code-pipeline changes. Batch-job changes still need an isolated test environment first.

The biggest open problem is uncertainty. When repository conventions do not settle a configuration choice, Scarlet sometimes proceeds without asking. The next step is to make that rule explicit in the skills and check it with regression tests on every release.

Takeaways

Slack made the work visible. The skill library made it maintainable: a new repository no longer needs a new agent, and teams review the files that hold their conventions. If you are building something similar, keep the model for the judgment calls and write every convention down as a file someone can review.

What’s next

The first post drew the line at anything that changes production: those actions wait for a human. With CI and data validation now in place, we think that line can move for routine work. Now that requests can start from tickets or other agents, every Scarlet MR will pass through one risk-based approval gate:

  1. CI passes.
  2. Scarlet’s data validation returns pass. A fail or inconclusive verdict goes to a human.
  3. The change is routine. New pipelines, rewired sources, and data contract changes always go to a human.
  4. A change that passes all three checks could move through review faster, with an engineer still making the final call to merge.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

The bridge to agent-scale Git infrastructure

Post Syndicated from Eleanor White original https://github.blog/engineering/architecture-optimization/the-bridge-to-agent-scale-git-infrastructure/


Over the past year, while Git traffic grew exponentially, 99.99999% of the Git repositories on GitHub began living in two places at once: our own data centers and Azure. The rest are among the busiest on the platform, and they’re held back by just one thing: a 25ms round trip.

In an earlier blog post, we laid out the two principles behind our next-generation storage architecture:

  • Minimize coordination
  • Decouple storage from compute

In this post, we’ll look at the immediate bridge between our old design and our new one. We’ll talk about how a change to the way our quorum serializes writes gets the busiest repositories into Azure, and how that same step opens the door to replicas that keep no persistent state of their own.

How we got here

The timing and shape of the move were driven by the agentic shift: rapidly growing traffic, a hard ceiling on the power capacity of our data centers and the surrounding geographical region, and physical supply chain constraints. At the beginning of our migration, the remaining capacity with all possible expansion gave us enough time to migrate safely, but not enough to do it slowly.

While we had prototyped new architectural approaches for scaling Git on cloud infrastructure, changing the storage architecture and the hosting platform at the same time, under that growth, carried too much risk. Given our scale and how critical the service is to the community, we needed to sequence the work carefully: move the data first, then evolve the architecture once it arrived.

Git operations are a Tier 0 service: they’re a core function of GitHub, and nearly everything in GitHub depends on the repository data. That meant the data, services, and every dependency had to move first. The first copy of a repository landed in Azure’s Central US region in August 2025. Today, most repositories have two of their five replicas in Azure, and Azure serves about half of Git traffic. For most of that time, Azure absorbed our growth while our own data centers held steady.

During the migration, traffic follows the data. Most repositories have five replicas to balance durability, availability, and scale. To minimize read latency, Spokes uses preferential routing to direct traffic to a replica in the same region and availability zone as the request. As replicas move to Azure, the share of the traffic that can be served from Azure grows with each one, until the last replica arrives and the old region stops receiving requests entirely. Every repository goes through this process:

No repository left behind

So, what about the remaining 0.00001% of repositories?

In our current architecture, a repository hosted in more than one region has a lower write throughput ceiling. Spokes’ quorum only needs a majority to commit a write, but it waits for every healthy replica to respond (up to a timeout) before moving on, so slow replicas delay every write rather than falling behind. In practice, that means the slowest healthy replica sets the latency of every write, and because each write holds a repository-wide lock until it commits, it also sets the throughput ceiling. Once a replica lives in the target Azure region, it’s about 1,000 miles from our data centers, making each network round trip around 25ms, and a write requires multiple round trips. A repository already near its throughput ceiling can’t absorb that on every serialized write; it would fall further behind with every push.

This is where our first principle, minimizing coordination, comes into play. Specifically for this case: don’t serialize what doesn’t need to be. Git’s consistency requirements apply to each reference individually. Once the server accepts an update to a reference, no client should see an older value afterward, only that value or a newer one. That holds whether the update is a fast-forward, a force push, or a delete. But in most cases, updates to different references don’t depend on each other and can be applied independently.

So, we’re changing the scope of the quorum from the whole repository to individual references.

Holding a repository-wide lock for the entire reference update, round trips included, turns the quorum into a single, unordered request queue with one write in flight at a time. Each write in that queue takes as long as the slowest healthy replica. As the write rate grows, so does the queue, and each write waits longer than the one before it.

With per-reference serialization, only writes that contend on a shared reference must wait for each other. In practice, most writes to a repository touch different references—for example, agents and developers pushing to their own branches—so they no longer wait on each other. Each write still experiences the cross-region latency but writes to different references can be in flight at the same time. That removes the single bottleneck on the repository. We can visualize how queueing and timeouts build up by comparing the two approaches side by side under similar load:

These changes raise a repository’s write throughput ceiling roughly in proportion to how many references are being written at once, and get the last remaining repositories into Azure. In internal testing with realistic traffic, writes to different references consistently saw 3–4x higher throughput at lower latency.

Scaling reads on their own

Most repositories are heavily read-skewed, with somewhere between 100 and 1,000 reads for every write. Today, reads and writes hit the same replicas, so they compete for the same resources and can’t be scaled independently.

Decoupling storage from compute changes that. Once repository data is durably stored in Azure Blob Storage and updated with each incoming write, we can begin to decouple read traffic from the write quorum, and independently scale the compute needed for each. For example, reads would benefit from far more in-memory cache than we give them today, but that memory is also needed for compaction. Once they’re separated, each gets its own configuration.

The first step is making object storage a member of the quorum, but a special one that we call a virtual replica. The compute that represents it is our first fully ephemeral node. It serves as a bridge to object storage, streaming incoming writes and serving no reads. Because it’s a member of the quorum, a write isn’t acknowledged until it’s durable in object storage.

That adds a little latency to each write, but just like the cross-region round trip, per-reference serialization keeps it from becoming a throughput bottleneck. The virtual write replica also coalesces transactions on disjoint references into a single set of network I/Os to object storage, so a busy repository pays for one round trip across many concurrent writes instead of one per write. For now, the virtual write replica also handles compaction, and read replicas inherit the compacted state.

With the virtual write replica in place, we can scale out as many virtual read replicas as a repository needs, on demand. Each read replica warms its cache from Azure Blob Storage and starts taking read traffic without joining the quorum, using object storage as the source of truth and reconciling its local state against it in the background.

This step unlocks significant read scale. In internal testing, our distributed load testing harness routinely found ceilings in the current architecture. Against virtual read replicas, the harness hit its own limits first. It also comes with a few challenges that are solved in subsequent steps:

  1. Virtual read replicas start out reconciling with object storage in the background, which makes them a good fit for some read workloads but not all of them. Serving every kind of read requires moving that reconciliation in-line, fetching only the reference state and data that changed since the replica last caught up.
  2. While we’ve incrementally increased write throughput by shifting to a per-reference model, the quorum remains the bounding factor for increasing further.

How can we push write throughput further?

What comes next

The GitHub of today was built on the Spokes quorum, and over the years Spokes has become much more than a quorum coordinator. It’s also an intelligent routing and load balancing layer, a unified API that internal clients use to access and transact repository data at well over 100 billion operations per day, and a collection of background systems we call “sweepers” that handle repository placement, repair, and rebalancing between storage nodes.

The vast majority of what lives under the Spokes service umbrella applies just as well to the new architecture as it does to the existing one. But we also recognize that the commit protocol that has taken GitHub to a billion repositories won’t take it to the next billion and beyond.

We’re not done yet. With these steps in place, the next limit is write throughput. Every write still waits on replicas that each hold a full copy of the repository, yet very little of a write actually needs to be ordered. Git objects are immutable and named by their contents, so they can be stored without anyone agreeing on them. What’s left is small, and the hard part is ordering it as fast as possible without moving the bottleneck somewhere else. Designing for that on a whiteboard is one thing. Doing it underneath a billion repositories that developers and agents are writing to around the clock is another. Getting there forced us to rethink the second-order effects too, like where durable reference state lives and how compaction and garbage collection scale.

Agent traffic isn’t slowing down, and each of these steps gives repositories more headroom as it lands, without waiting for the end state.

Coming next week: At GitHub Universe and in the final post in this series, we’ll take a tour through that end state, what it does for write throughput, the second-order problems we had to solve to get there, and why there’s still a (small) consensus group somewhere in the stack.

Thanks to Brian Celenza for their contributions to this post.

The post The bridge to agent-scale Git infrastructure appeared first on The GitHub Blog.

App stability at scale with a layered defense

Post Syndicated from Grab Tech original https://engineering.grab.com/app-stability-at-scale-with-a-layered-defense

Introduction

Artificial intelligence (AI) coding assistants have changed how fast we can ship. They have not changed how mobile users experience a crash. That gap is the pressure every mobile stability program now operates under.

The Grab superapp, which millions of users across Southeast Asia use to book rides, order food, and more, operates at a large scale. On Android alone, it spans millions of lines of code, with many engineers shipping code into every release on a weekly release cycle. Maintaining app stability is not just a technical goal; it is a product commitment to those users. With the rise of AI coding assistance, the volume of change in every release has grown, and so has the number of ways a single change can break something in an already large codebase.

At this scale, crashes leaking into production are an ongoing risk. A high volume of merge requests lands every week across many product teams, many shipping features behind flags that are switched on independently of releases. Any one of those changes can introduce a crash. Most of the time, the stack trace points straight to the responsible change and team. The hard cases are the exceptions: crashes without a usable stack trace, such as native crashes without debug symbols, where finding the cause means cross-referencing release timelines, flag rollouts, and session metadata.

The cost of a crash is also steeper on mobile than on the web. A web fix can go live in minutes; a mobile crash that ships stays on users’ devices. With more than 100 million downloads on Google Play as of October 2026, not every user has auto-update enabled, and until a force update reaches them, some will run a broken version for months. Meanwhile, the crash degrades their experience, drags down the crash-free session rate, and can hurt the app’s ranking on Google Play. If it is severe enough to need a hotfix, the team also has to prepare an out-of-cycle build, pulling time away from planned work.

We keep the Grab superapp stable with a set of layered practices. Data points and tooling examples come from Android. The Grab iOS app follows the same strategy with platform-equivalent tooling (SwiftLint in place of Android Lint), and both apps share one release pipeline for Grab Early Access (GEA), our early access build, as well as staged rollout, production monitoring, and crash triage.

A layered defense for app stability

Our strategy is rooted in a shift-left mindset: the earlier we catch a crash, the cheaper and less disruptive it is to fix. A crash caught by a lint rule costs nothing. A crash caught in GEA takes an engineer fewer hours to fix. A crash that reaches production costs user trust. That is why we invest most heavily in prevention: the goal is to stop crashes before they reach production, not to fix them there.

The system is a series of filters, each anchored to a specific phase of the feature development lifecycle, so the right check runs at the right time, and a crash that slips past one layer has another waiting downstream.

The colors mark the three phases on the stability side: prevention (pre-merge through pre-prod), the release gate (staged rollout and feature flags), and response (post-release).

Prevention: Our primary line of defense

Lint checks: Stopping crashes at the code level

Lint is the cheapest layer we have: static analysis that flags unsafe patterns, application programming interface (API) misuse, and likely crashes before the code ever runs. We use Android Lint on Android and SwiftLint on iOS. Both run in continuous integration (CI) on every merge request, and high-severity findings are merge blockers. Pre-existing issues never block a merge request: on Android, a lint baseline records them, and on iOS, SwiftLint reports only on the lines a merge request changes. Either way, a merge request fails only on the findings it introduces.

Our rules come from three sources:

  • Platform rules. Built-in checks cover well-known dangerous patterns, such as incorrect API usage and threading mistakes, and form the foundation for every build.
  • Community rules. Open-source rule sets cover third-party libraries and patterns the built-in checks miss. We adopt the ones relevant to our stack.
  • Custom rules. Both Android Lint and SwiftLint support custom rules, and we have built our own on both platforms. When a post-mortem or crash investigation traces a production crash to a specific code pattern, we write a rule that blocks that pattern from coming back.

Custom rules matter more as AI-assisted coding grows. An assistant can write code that looks right in general without knowing which patterns have crashed our app before. Custom rules turn those lessons into checks that apply equally to hand-written and AI-generated code.

Lint routinely blocks merge requests carrying Fatal issues: the kind that typically crash the app immediately or stop it from running.

Testing strategy: Multiple layers of confidence

Lint catches unsafe patterns statically, but it cannot run the code. Tests are where we catch crashes and regressions that only appear at runtime. No single test type covers everything, so we apply multiple complementary layers:

Layer Focus
Unit tests Business logic correctness at the function and class level
User interface (UI) component tests Rendering and interaction behavior of individual UI components
End-to-end (E2E) automation tests Integrity of critical user journeys
Quality assurance (QA) manual testing Real-device exploratory testing for new features and significant code changes

Each layer targets a different class of crash risk. Unit tests block logic errors before they merge. UI component tests catch crashes tied to rendering or state mismatches; like unit tests, they run pre-merge on every merge request, so a rendering regression is blocked before it lands. E2E automation covers the flows with the highest business impact and runs on a per-team schedule and on every release train. QA manual testing focuses on new features and significant code changes, plus a full regression pass on every release, catching the edge cases that automation misses on real devices.

Grab Early Access (GEA): A one-week pre-production gate

Even with strong lint rules and test coverage, some crashes only surface under real-world conditions. GEA is an early build app by Grab. GEA builds are actively monitored for crashes, and any new crash surfaced during the GEA window automatically creates a ticket assigned to the responsible team. Issues reported by internal users, including functional defects and feature breakage, are ticketed the same way. Teams are required to resolve all blocking GEA issues before the release proceeds to production. GEA’s user base is large enough to expose real-world edge cases that automated tests miss, but small enough that issues are contained before reaching production users. GEA is a mandatory quality gate on every release cycle.

A crash that only a handful of internal users see in GEA would, at production scale, translate into a substantial spike in the crash rate, extra support load, and potentially a hotfix. Catching these crashes before they ever reach production users makes GEA one of our most important stability gates.

The impact adds up. Across both platforms, GEA catches new crashes every month, and each is fixed before the release reaches production. Each of them could otherwise have reached production users, including the long tail of users who do not auto-update and would have kept hitting them for months.

The release gate: Staged rollout and feature flags

Prevention keeps crashes out of the build. But the moment a release enters production, it meets something neither lint rules nor GEA can fully replicate: the full diversity of the real world, with thousands of device models, operating system (OS) versions, carrier configurations, and usage patterns that no internal test environment can mirror. So we treat the release boundary as its own critical checkpoint, a release gate between a validated build and full user exposure. Two mechanisms operate at this gate: staged rollout monitoring to limit the blast radius of the release itself, and feature flags to decouple feature activation from deployment.

Staged rollout monitoring

We do not ship to all users at once. Every release follows a staged rollout over the course of a week, starting with a small percentage of users and expanding in steps to the full user base. Each increment gives the monitoring system time to accumulate meaningful signal before the next expansion. During this window, we run a dedicated monitor that tracks the crash rate of the new version in isolation, separately from the baseline of all active versions. The separation matters: a regression in the new release can be masked in aggregate metrics if the older, stable versions dominate the user base.

If the new release shows an abnormal crash rate at any point during rollout, an automated system pauses the release before it expands further. The rollout does not resume until the responsible team has reviewed the issue and explicitly approved continuation. The pause gives us a hard stopping point: a regression introduced by the new release is contained to the fraction of users who received it, instead of compounding across the full install base.

In recent months, several Android rollouts were paused for on-call review. Most resumed after investigation: either the signal turned out to be noise, or the crash sat behind a feature flag that could be turned off without a new build. A small number stayed halted at the first stage until a hotfix shipped. We tune the monitor to be sensitive on purpose: a paused rollout takes an engineer a few hours to fix, while a missed regression can cost weeks. In one of the halted cases, only a small number of users hit the new crash before the halt, and the rest of the user base never saw it. Without the automated halt, the rollout would have kept expanding on schedule, taking the crash to the full user base.

Feature flags: Controlled activation with an instant kill switch

Even when a release ships cleanly, the features inside it are gated independently. All significant new features ship behind feature flags, decoupling deployment from activation. Flags let us roll out a feature gradually, monitor crash rates at each increment, and, critically, disable a feature instantly if its crash rate exceeds a defined threshold, without waiting for the next release cycle. For a team shipping weekly, the kill switch is what makes fast iteration safe, and it is also our first lever when something does reach production.

Response: When prevention falls short

No prevention layer is perfect. Crashes can still reach production: a misconfigured remote flag opens an unexpected code path, an OS update from a device manufacturer changes system behavior in ways no test environment can predict, or a bug slips past GEA and the rollout monitor because it only triggers under a specific combination of device state and user action. When that happens, the goal shifts from prevention to containment. For these scenarios, speed of detection, stopping the bleeding, and accuracy of diagnosis become the priority.

Real-time monitoring and on-call response

We maintain real-time crash rate monitoring across all active versions, with two complementary signals that can trigger an on-call alert:

  • Hard threshold breach. The crash rate of an active version crosses an absolute limit we define as unacceptable.
  • Abnormal trend. The crash rate spikes sharply relative to its own recent baseline, even if it has not yet crossed the absolute threshold.

We watch both because they catch different failure modes. A hard threshold catches slow drift: if the crash rate creeps up a little with each release, every step looks normal against its recent baseline and the trend alert never fires, yet over a year the rate can quietly increase. An abnormal trend catches the opposite case: a sudden regression, early, before it grows large enough to breach the threshold.

When either signal fires, an on-call engineer is immediately notified. The engineer begins by reviewing Firebase Crashlytics reports to identify which crash issues are driving the anomaly, then loops in the team responsible for the affected area. From there, the response follows a three-step decision framework, ordered from cheapest to most expensive:

  1. Disable the responsible feature flag. If the crash is tied to a feature behind a flag, turning the flag off stops new users from hitting the issue immediately, with no new build required. Turning off a flag is by far the fastest mitigation we have.
  2. Apply a server-side fix. If no flag covers the affected code path, the team looks for any server-side lever that can contain the impact: updating an API response, changing a config value, throttling a backend dependency. Any change that takes effect without shipping a new app build is preferred over one that does.
  3. Ship a hotfix. If neither of the above is available, the team evaluates whether the crash warrants an out-of-cycle hotfix release, using defined criteria: business criticality of the affected flow, crash severity, user impact, and time to the next scheduled release. After the hotfix is delivered, a post-mortem is required. The goal is not just to document what went wrong, but to identify concrete action items that close the gap in our prevention layer, such as adding a lint rule to block the same pattern, wrapping a similar feature behind a flag, or improving test coverage for the affected code path. Every hotfix should make the next one less likely.

Automated crash triage

Automated ticket creation in GEA and production is not a collection of separate tools; it is one triage pipeline that follows a release from GEA into production. In production, running in parallel with real-time monitoring, it creates a production issue ticket for crashes that cross a minimum threshold. We assess crashes by type, user impact, and whether they’re actionable. Tickets are created for issues that meaningfully affect users; low-volume, device-specific crashes that we can’t address are monitored but don’t receive tickets. This keeps the team focused on the problems users are most likely to feel.

For crashes that do qualify, the ticket is routed to the owning team with a service-level agreement (SLA) tied to severity: Urgent, High, Medium, or Low. The initial priority is set automatically based on crash rate and user impact, but teams can re-evaluate and adjust the priority based on the business criticality of the affected feature.

Feature flag rollout history: Diagnosing crash spikes

Some of the hardest on-call moments start the same way: the app suddenly begins crashing, alerts fire, and there is no obvious reason why. Nothing shipped that day, and in the worst cases the crash arrives without a usable stack trace to point anywhere. With many product teams working on the same app simultaneously, the culprit is often not new code in the latest release; it is a feature flag quietly rolled out to a wider user segment in the background. Finding that flag by asking around does not scale: without a central view, an on-call engineer can spend hours before the responsible rollout turns up.

So we maintain a feature flag rollout history: a dashboard that correlates flag activation events with crash rate changes over time. Instead of polling every team, the on-call engineer gets an immediate view of whether any flag rollout aligns with the onset of the spike, turning a slow manual search into a quick read of a timeline.

Deep observability: Enriched diagnostics for hard-to-debug crashes

Firebase Crashlytics is our primary crash monitoring tool, but some crashes resist easy diagnosis: crashes with unusable stack traces, native crashes from third-party libraries without debug symbols, or issues that only manifest on specific device configurations. Without a clear stack trace, there is no obvious starting point for investigation.

We handle these cases in two ways.

First, we use Crashlytics’ built-in export to BigQuery, so we own a copy of the crash data. The data is pseudonymized and handled under Grab’s data protection policies. That copy gives us two things Crashlytics alone cannot:

  • Query the data when needed: full Structured Query Language (SQL) analysis across device attributes, app versions, and session metadata, surfacing patterns invisible in individual crash reports.
  • Build internal dashboards that serve app stability investigations, broken down by crash category, device tier, or release version.

Second, we enrich every crash session with custom metadata attached directly to Crashlytics. Among the most useful attributes we track:

  • Last visited screen: the last screen the user was on before the crash occurred (for example, the last Activity and Fragment on Android), helping reconstruct the navigation path that led to the failure.
  • Install source: whether the app was installed from Google Play or a third-party store (Android only). Some third-party stores distribute unofficial copies of the app, and more than once we have traced a crash back to a corrupted copy served by one of them. Knowing the install source lets us recognize these failures as environmental, instead of chasing them as code defects.
  • Session history: from the session data, we can reconstruct the sequence of screens and actions leading up to the crash, which is often the key to a crash investigation.

We attach many other custom attributes, but these three have proven the most useful in hard investigations. Together with structured logs and breadcrumbs, they give us a trail of events leading up to the crash, often the only meaningful signal when the stack trace alone is not enough.

Crashes we control, not eliminate

Different crashes call for different responses. Some are fixed in our code, while others, such as rare native crashes in operating system (OS) code, out-of-memory errors on devices near their limits, or failures from unofficial and sideloaded installs, are better handled through monitoring and containment.

We keep these categories at an acceptable baseline and monitor them on dedicated dashboards, separate from actionable issues. If any of them starts trending up instead of sitting flat, that spike triggers the same triage process as any other anomaly.

Conclusion

Sustaining stability across a codebase of millions of lines on Android alone, with many engineers shipping a release every week and AI assistance accelerating the rate of code change, is not the work of any single tool or team. It is the cumulative effect of a layered defense: lint rules and tests blocking bad code at the merge gate, QA and GEA catching what slips through, staged rollout limiting the blast radius of what reaches production, and on-call response combined with automated triage closing the loop on what production reveals.

The principle behind every layer is the same: shift left. A crash caught earlier is cheaper, smaller in impact, and less disruptive to fix. As the volume of code shipped per release continues to grow, the layered defense matters more, not less: the cost of a crash that reaches production is unchanged, but the number of opportunities to introduce one is rising. AI is speeding up how fast code is written; the layered defense is what makes that speed safe. Stability is not about having zero open problems; it is about knowing which problems you own and which ones you are watching.

Join us

Grab is a leading superapp in Southeast Asia, operating across the deliveries, mobility, and digital financial services sectors. Serving over 900 cities in eight Southeast Asian countries: Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam. Grab enables millions of people every day to order food or groceries, send packages, hail a ride or taxi, pay for online purchases or access services such as lending and insurance, all through a single app. We operate supermarkets in Malaysia under Jaya Grocer and Everrise, which enables us to bring the convenience of on-demand grocery delivery to more consumers in the country. As part of our financial services offerings, we also provide digital banking services through GXS Bank in Singapore and GXBank in Malaysia. Grab was founded in 2012 with the mission to drive Southeast Asia forward by creating economic empowerment for everyone. Grab strives to serve a triple bottom line. We aim to simultaneously deliver financial performance for our shareholders and have a positive social impact, which includes economic empowerment for millions of people in the region, while mitigating our environmental footprint.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Staying Evergreen: How we automated secure access and repo hygiene in a shared org

Post Syndicated from Greg Mohler original https://github.blog/engineering/platform-security/staying-evergreen-how-we-automated-secure-access-and-repo-hygiene-in-a-shared-org/


Working with outside collaborators can add more work for a repository owner. You need to confirm who still needs access, change permissions as projects evolve, and archive repositories once they’ve served their purpose.

To keep up, repository owners need to track collaborators, deadlines, and follow-ups for each repository. As a project grows, that manual housekeeping becomes harder to keep up with and easier to defer.

We faced this problem in a shared organization where GitHub employees (“Hubbers”) collaborate with customers and partners on product trials and professional services engagements. Our answer was Evergreen, a GitHub App built with native GitHub features. The workflows below exhibit a pattern you can adapt for your own organization.

Meet Evergreen

Evergreen is a GitHub App that automates organization hygiene through two workflows:

  1. Outside collaborator access reviews. Every quarter, each repo’s outside collaborators are reviewed. Keep who you need, and everyone else is removed.
  2. Stale repository detection and archival. Repos with no human activity past a threshold get flagged, warned, and (if still untouched) archived.

Two design principles shaped everything:

Fail secure. If nobody responds to an access review, we don’t leave access in place and hope for the best. We revoke it. The safe outcome is the default outcome.

Never destroy anything. Evergreen will never delete a repository or its contents. Archived repos are recoverable, and every access change is written into the repo’s tracking issue, so reverting a mistake is as easy as a copy-paste to Copilot.

How it works: One brain, many hands

Under the hood, Evergreen is a small Go webhook server running in a container. But the interesting part is the choreography. Every moving piece is a stock GitHub feature: a GitHub App, scheduled actions, webhooks, issues, custom properties, and plain files in a repo. Nothing exotic to reinvent.

A controller that keeps time

A dedicated controller repo acts as Evergreen’s clock and its memory. Four scheduled GitHub Actions workflows fire repository_dispatch events on a quarterly cadence, and the app wakes up and does the work:

Day Workflow What happens
1st Stale repo review Flag repos with no recent human activity, open a warning issue
8th Access review Snapshot outside collaborators, open a checklist issue per repo
16th Stale repo cleanup Archive repos still stale after the grace period
23rd Access cleanup Auto‑revoke access for any review left unanswered

Reviews open two weeks before their cleanup runs, and there’s a hard grace period baked in so a stray manual run can never fast‑forward the guillotine. Each workflow also supports workflow_dispatch, so we can trigger any step by hand as needed.

State you can git blame

Evergreen tracks every repo’s status as a JSON file (one per repository) committed to the controller repo under state/repos/<repo_id>.json. The snapshot of who had access, when the review opened, the deadline, who decided, and what happened all lives there. Here’s a completed review where a Hubber kept Alice’s access and let Bob’s lapse:

{
  "repo_id": 123456789,
  "full_name": "the-org/acme-trial",
  "last_seen_at": "2026-04-13T00:05:00Z",
  "access_review": {
    "deadline": "2026-04-27T00:00:00Z",
    "status": "renewed",
    "collaborators_at_open": [
      { "login": "alice", "name": "Alice Example", "permission": "admin" },
      { "login": "bob", "name": "Bob Example", "permission": "write" }
    ],
    "renewed_logins": ["alice"],
    "decided_by": "carol-hubber",
    "decided_at": "2026-04-15T16:42:10Z",
    "tracking_issue": { "repo_id": 123456789, "number": 42 }
  },
  "staleness": {
    "last_activity_at": "2026-04-15T16:42:10Z",
    "warned_at": null,
    "archive_deadline": null,
    "status": "active",
    "tracking_issue": null
  }
}

The best part: because state is just files in git, the commit history is the audit trail. Want to know why someone lost access last spring? git log the state file. There’s no separate database or bespoke audit pipeline to track.

Issue‑ops, everywhere it matters

Evergreen does its talking through issues inside each repository. When an access review kicks off, every repo gets a checklist issue:

Screenshot of an access review issue titled “[ACTION REQUIRED] Access Review – 2026-04-13.” Outside collaborators Alice Example, with admin access, and Bob Example, with write access, have unchecked boxes. Instructions say to select anyone who should keep access, then close the issue. A warning states that if no action is taken by April 27, all listed access will be automatically revoked.

The interaction model is delightfully simple: check the boxes for who stays, then close the issue. That’s it. When the issue closes, Evergreen listens for the issues.closed webhook event, reads the checkboxes, retains the checked collaborators, and revokes the rest, then posts a receipt comment listing exactly what it kept and what it removed.

Quarterly outside-collaborator access review flowchart. A dispatch snapshots outside collaborators and opens a checklist issue in each repository. If a team member closes the issue, checked collaborators retain access and unchecked collaborators have access revoked. If no one responds by the deadline, everyone’s access is automatically revoked. Both paths log the decision in the issue and state.

Only the right humans can pull the lever

Closing an access review issue is a privileged action, so Evergreen guards it. If someone who isn’t a Hubber closes an issue, the app quietly reopens it and posts a note explaining why. Decisions only count when they come from the people authorized to make them.

Informing the right people

Here’s a subtle problem: we know the people who need to respond to a review are Hubbers, but we didn’t always know which Hubber(s) owned a given repository.

Evergreen resolves the right people to notify through a fallback chain:

  1. If a repo sets an evergreen_repo_owner custom property (a @user or @org/team), use it.
  2. Otherwise, look at recent issue and commit authors and cc the ones who are on the access review team, i.e., the Hubbers actually working in that repo.

The result: the right owners get pinged automatically, without anyone maintaining a spreadsheet of “who owns what.”

Fail secure, and fail closed

When a review deadline passes with no response, cleanup revokes every collaborator in the snapshot. We were careful about a subtle edge case: what if some removals succeed while others hit a transient API error? Marking the review “done” while a removal is still outstanding would be a quiet inconsistency, and we didn’t want that.

So Evergreen fails closed. If any removal fails, the review stays pending and the issue stays open, and the next run retries the stragglers. It only records “revoked” once every removal actually succeeded. And whatever gets removed is written into the issue, so restoring access is a matter of re‑adding the handles it listed.

The user experience: automation that feels considerate

Automated housekeeping has a reputation for being the office smoke alarm: loud, easy to ignore, and usually going off while you’re cooking something perfectly fine. We worked hard to make Evergreen feel like the opposite:

  • It comes to you. The work happens as an issue in your repo.
  • It tags the right people. No “who owns this?” archaeology.
  • It’s crystal clear about the ask. Every issue states what to do, the exact deadline, and precisely what happens if you ignore it.
  • It nudges before it acts. A reminder comment lands before the deadline: no surprise revocations.
  • It has an escape hatch. Org owners (Hubbers) can opt out by setting a custom property (evergreen_exempt_from_access_review or evergreen_exempt_from_archive).

Rolling it out carefully

Automation that manages access and archives repositories deserves a careful rollout, especially into a large, active org (ours has 1,400+ Hubbers, and many more customers and partners). We wanted the very first run to be a complete non‑event. A few practices got us there:

Dry‑run first. Evergreen ships with a DRY_RUN mode that logs every write it would make without touching a single collaborator or repo. We ran it against the real org and read the logs like tea leaves until we trusted the decisions it wanted to make.

Overcommunicate. Before flipping the switch, we broadcast what was coming, when, and what people needed to do, so the first issue anyone saw wasn’t a surprise. We found that when you’re telling a large group the same thing for the seventh time, it’s often when many are still hearing it for the first time.

Watch everything with Splunk. Evergreen emits structured logfmt logs to a dedicated Splunk index. That observability is how we caught edge cases in the wild (empty collaborator lists, unusual permissions, repos with issues disabled) and tightened the logic before they mattered.

Respect the platform’s speed limits. When you open issues and post comments across every repo in a big org, you slam into GitHub’s secondary rate limits for content creation: 80 requests/minute and 500/hour. While this is a thoughtful preventative control to avoid system abuse, it requires a bit of intention when automating IssueOps at large scale.

So Evergreen paces itself by construction. It processes repos in batches, spaces out each content‑creating call by a couple of seconds, and sleeps between batches to let the rolling window clear, and it only counts the repos that actually create content, so a quiet quarter where nothing’s eligible still runs fast. We opted for proactive avoidance over reactive back‑off.

Lessons we’re taking with us

  • Make the safe path the default path. Fail secure, then make responding easy enough that failing secure rarely triggers.
  • Use the primitives you already have. Issues, webhooks, custom properties, and git history did the work of a bespoke UI, a job queue, and an audit database.
  • Meet people where they work. An issue in your repo beats a dashboard you’ll never open.
  • Logs are a revert button. Writing every change into the issue turned “oops” into “paste these three handles into a Copilot session.”
  • Respect the limits. At org scale, rate limits aren’t an edge case: they’re the design constraint.

Keep your org evergreen

Routine hygiene is the kind of work that’s easy to defer and perfect to automate. The trick isn’t heroic cleanup sprints: it’s making the boring, safe thing happen on a schedule, with a friendly face and an undo button.

That’s Evergreen. And because it’s built entirely from native GitHub features, you can stand up the same pattern yourself.

Ready to make repository hygiene routine? Start with one recurring access or archival task, then use GitHub Apps, actions, issues, and custom properties to automate the problem away.

The post Staying Evergreen: How we automated secure access and repo hygiene in a shared org appeared first on The GitHub Blog.

From 2,500 requests to 24: Rebuilding star history without the stargazers

Post Syndicated from Taylor Cuilty original https://github.blog/engineering/architecture-optimization/from-2500-requests-to-24-rebuilding-star-history-without-the-stargazers/


Maintainers look at star history to answer a practical question: did a launch, release, or event change a project’s trajectory? To reconstruct that curve from the GitHub API, tools had to request pages of stargazer records (each person who currently stars the repository and when they starred it), keep the timestamps, and throw the identities away.

Over time, that design created problems at both ends. Identities were available for bulk collection, so bad actors started scraping public stargazer lists for spam and phishing campaigns. For highly starred repositories, the endpoint could also make the database process many thousands of entries to return a single page.

The fix seemed clear: return counts instead of people. But returning less data didn’t actually make the query any cheaper.

Now maintainers have a direct way to get the curve: we built an endpoint that returns up to 30 weeks of daily star counts in a single request, with no identities attached. Keeping that cheap to serve meant reducing how much data the database processed, not just how much it returned, and the endpoint does that by filtering stars by time before it counts anything.

What maintainers need from star history

We first addressed the immediate risks to developers and to our database by restricting stargazer and watcher lists to repository administrators and collaborators. After the access change, callers without the required permission could receive an empty response or a 403 Forbidden response.

That change also cut off tools that had used the old response to calculate star history, often without displaying or otherwise using the usernames it returned. So we talked with maintainers and tool builders to understand what they still needed. They used star history as an approximate signal of interest: to compare activity before and after a release, or to see whether an announcement reached new developers. What they cared about was the curve.

The old API response had made identity look like part of that contract because every timestamp arrived attached to a user. In practice, tools such as Star History needed counts and dates, not usernames or other user data. Once identity was no longer part of the requirement, we could design an aggregate endpoint for the actual job: retrieving changes in star counts over time at a useful resolution.

When the API change disrupted Star History, users rallied around the project. GitHub’s Community team listened and connected us with product engineering, who dug into our use case and worked alongside us to design a purpose-built endpoint. A difficult situation became a constructive collaboration between GitHub, Star History, and the broader community—ultimately leading to a better solution.

Tianzhou Chen, star-history.com maintainer and Bytebase co-founder

Why the original endpoint was expensive

Once we knew what maintainers needed, the next step was understanding why the original design couldn’t provide it cheaply. The original GET /repos/{owner}/{repo}/stargazers endpoint was built to answer a simple question: who starred this repository? It returned a paginated list of people, and if the request specified a custom media type, each entry also included when the star was created.

The star model was built for the same job. It records the current set of people who have starred a repository, which keeps showing a star count or a list of stargazers simple. It was not designed as a historical event log: when someone removes a star, that record is removed. When tools began using the list as a time series, reconstructing a growth curve meant retrieving individual identities and processing every current star. Because each page held at most 100 people, the work grew with the repository’s popularity: building the full curve for react/react, with about 251,000 stars, took about 2,511 requests, so tools often ran into rate limits or sampled pages instead of reading them all.

Serving a page required the database to query the repository’s current stars. Due to a bug in the pagination implementation, every request also counted all of those stars to work out how many pages existed, even though the caller received only one page of up to 100 people. On a highly starred repository, that meant counting many thousands of entries on every request. In the week before we restricted access, nearly 37,000 of these count queries ran slowly enough to be logged, averaging nearly 3 seconds each, and database safeguards killed more than 1,000 of them, which contributed to request timeouts.

The chart below shows what all that counting cost. After we restricted access, the database served about 60% fewer stargazer requests, and the total time it spent on the count query fell by about 80%.

Approaches we considered

Removing identities handled the privacy requirement. The harder part was keeping each request from scanning the repository’s entire current star set.

Keeping events without identities

Our first spike kept one record per star and returned the starred_at value without the stargazer’s identity for callers who lacked collaborator access. At first, this looked like the quickest path forward, because it directly served the request we had heard from tool builders. It also closed the identity-harvesting path with a relatively small change to the existing serialization and authorization flow.

This approach addressed identity exposure and would have allowed existing tools to keep working. But API consumers would still have to paginate through and process potentially many thousands of individual records to build an aggregate history. It also tied the new use case to an endpoint and pagination model designed for listing people rather than retrieving trends.

Aggregating, then paginating

Aggregation seemed like the obvious next step. Instead of returning one row per star, the query could group stars into daily or weekly buckets, sort those buckets, and paginate the much smaller result.

The problem was where pagination happened. In a straightforward SQL query, the database first finds all stars for the repository, groups them into buckets, and sorts those buckets. Only then does it apply LIMIT, which controls how many buckets are returned, and OFFSET, which determines where the page begins:

all matching stars -> bucket every row by day or week -> sort every bucket -> OFFSET/LIMIT -> response

For a popular repository, an anonymous request could still scan and aggregate many thousands of index entries to return a handful of buckets. Returning fewer buckets would shrink the JSON response, but it would not reduce the expensive grouping and sorting the database had already performed. For react/react, reading the full history that way would have meant examining roughly 6 million rows, because every one of the 24 requests would have reprocessed all of its stars. To reduce the query cost, we had to narrow the rows before aggregation began.

Filtering by time before grouping

The design we shipped paginates star history by calendar week. For each request, it translates page and per_page into an indexed created_at range, filters the stars to those weeks, and then groups the matching records into daily counts. A response includes up to 30 weeks, and increasing page moves backward through the repository’s history.

indexed date range -> group rows in that range -> daily buckets -> response

With the date range applied first, each request processes the weeks being returned instead of every current star in the repository. For tools, that means one request now covers up to 30 weeks of history, no matter how many stars the repository has. For react/react, that’s about 24 requests instead of about 2,511, and the database examines each star about once (roughly 251,000 rows) across the full history. This fits the primary use case because maintainers usually inspect growth across weeks or around a known release, launch, or event. Week-based ranges also align with other repository activity APIs: the response follows the same shape as the weekly commit activity endpoint, GET /repos/{owner}/{repo}/stats/commit_activity.

The time-range design limits each request to a defined period, but it does not limit the number of stars within that range. A week with an unusually large number of stars can therefore still produce a slow or expensive query. The normal request path no longer queries every current star, but exceptionally dense weeks remain a scaling limitation.

Comparing the performance of the old and new API paths also surfaced other places where GitHub was counting stars on demand. We found the same pattern on the repository stargazers page on GitHub.com and updated it to use the repository’s cached star count. Slow queries from that page, which had numbered in the hundreds each week, dropped to zero. We recently shipped a similar fix to other stargazer API endpoints.

The chart below shows slow and killed stargazer count queries each week, by where they came from.

What we learned

  1. A smaller response does not always mean a cheaper query. LIMIT and OFFSET reduced the number of results returned, but they did not reduce the grouping and sorting the database had already done. We had to look at the order in which the work happened.
  2. Start with what people are actually trying to do. Maintainers needed to compare trends. A list of identities was simply how the old endpoint happened to provide the underlying data.
  3. Return only what the use case needs. Anything more is data someone else can misuse. Once we understood the job, we could remove individual identities without taking away the information maintainers relied on.
  4. Be clear about the tradeoffs that remain. The new endpoint is safer and more predictable, but calendar boundaries, removed stars, and unusually dense weeks still affect what it can return. Those details are part of the API contract too.

Restricting the original endpoint addressed the immediate problem. Listening to maintainers gave us something better than what we started with: star history that’s easier to get, cheaper to serve, and safer for everyone who stars a project.

Get repository star history, then share feedback in the GitHub Community discussion.

The post From 2,500 requests to 24: Rebuilding star history without the stargazers appeared first on The GitHub Blog.

Rewinding the exponential: How we keep hardware usage down

Post Syndicated from Cathy Chi original https://blog.cloudflare.com/rewinding-the-exponential/

More than 20% of the web sits behind Cloudflare’s network, and our team, the Data team, owns the data pipeline responsible for plumbing that data (and more) from our global network to applicable central data centers. The Cloudflare network is a globally distributed system supporting tens of thousands of servers. Data that power Cloudflare Logs, SQL API, observability, internal analytics, and more flow through this network and use our data pipeline to serve customers.

In May of this year, we were providing data delivery at roughly two billion events per second. This includes customer traffic as well as data sent from internal teams. Year after year, we tackle the same problem — exponential traffic growth against linear hardware growth. We have to react to this increase in order to keep resource costs under control. Over the past five years, we’ve made various improvements to compensate for the data volume increase in comparison to hardware allocation, equivalent to deferring two and a half years of hardware expansion. This post details those changes: breaking up our monolithic data schema in 2022, adjusting compression in 2024, rearchitecting pipeline replication in spring 2026, decentralizing sampling in summer 2026, and introducing aggregations into the pipeline in fall 2026.

Background

Our pipeline starts with an internal service called Logfwdr, where we collect from highly distributed data sources (think: Workers, FL). We then feed this data to a set of centralized receivers, which eventually push them onto our buffering system, Buftee. Consumers fetch data from Buftee and distribute data to their final destinations, like ClickHouse, which we rely on heavily.

Unpacking the monolith

In 2022, we dismantled our one and only schema. Previously, there was a single stream packed with every product's fields, forcing Cloudflare-internal consumers to ingest everything and demux or discard records via filters. At the time, most of Cloudflare’s data products were built on HTTP, Security and CDN metadata. In 2021, our message schema looked like this:

Some fields here belonged under the same product, but some were completely irrelevant to each other. The hypothesis was that none of these teams require 100% of fields in the monolithic schema. In other words, we can create small messages for each product’s required fields. Although we were going to duplicate fields, some of them in every message, replacing this firehose with product-specific schemas actually reduced the backbone bandwidth usage by 35-40%, knocking out roughly a year’s worth of compressed traffic growth.

Compression

By 2024, as traffic steadily grew, we were tackling network congestion issues on a daily basis. To react to this, we changed our compression algorithm from LZ4 to zstd. We had already experimented with zstd compression before, but we noticed a higher CPU usage at the time. Therefore, we were careful to track the metrics to ensure the trade-off was worth it.

Initially, we rolled this change out to a few servers. To our relief, we didn’t observe a noticeable difference in CPU usage.

With more confidence, we gradually rolled out to our entire fleet, which also showed little impact to CPUs. In the end, there was nearly a 40% reduction in compressed traffic throughput. The uncompressed bytes remained at the same growth, meaning we could support more than 1.5x the amount of traffic with the same size pipe. Or another way to put it, the estimated growth-equivalent reductions put us at about 10 months prior.

Now, in 2026, we attempted three strategies to reduce uncompressed bytes (and thus, compressed bytes).

Load balancing

To make analytics resilient against regional disasters, our systems require redundant data to be stored in multiple centralized regions (data subject to Customer Metadata Boundaries is stored strictly within its designated region). Historically, the simplest way to achieve disaster resilience was double-writing: Logfwdr transmitted two full copies of every non-regional analytics event — one to each centralized region. Each region then independently processed a complete copy through to ClickHouse. We also apply sampling in each region, an incredibly scalable technique that works for all volumes of data during any traffic conditions. We downsample high-volume traffic while rare events are preserved.

This infrastructure was manageable when only a handful of streams used secondary regions. However, as we expanded disaster resilience across almost all analytics streams, Logfwdr traffic doubled across the board. Sending every event, twice, over wide-area transit was unsustainable against our exponential traffic growth.

We had already tackled a similar challenge for Logpush. For Logpush, Logfwdr treats the centralized data centers as a unified, shared pool of receivers: each message is sent to only one region, failing over to another destination if a machine or facility is unreachable. That model had already proven its worth during large incidents, shifting traffic seamlessly from one location to another without human intervention. This automatic failover was possible because Logpush delivery is stateless, as customer destinations do not care which centralized data center pushes the logs.

Analytics was trickier. Unlike stateless logs, ClickHouse clusters in both regions still need a full copy of non-regional data to allow instant, independent query failover. The breakthrough was decoupling pipeline transit from database redundancy:

1. Shared Ingest Pool: We adopted Logpush’s model to the analytics streams. Logfwdr dispatches each event exactly once across wide-area transit to whichever centralized receiver is available.

2. Late Replication from centralized regions: Instead of replicating traffic at source, replication happens as late as possible in the pipeline. Data lands in our distributed buffering layer, Buftee, and remote inserters stream cross-data-center copies downstream.

3. Resilient Failure Handling: If a centralized region goes down, Logfwdrs immediately routes all non-regional traffic to the surviving region. If the inter-data center connection blips, each cluster continues ingesting its local share without backpressure; remote inserters catch up from Buftee's retention buffer once the backbone recovers.

For the datasets we migrated, the cutover eliminated approximately 43 GB/s of compressed transit traffic while adding only ~7 GB/s of cross-data-center replication on our pipeline. Two architectural factors explain this asymmetry:

1. Replication happens downstream of sampling: In the old model, Logfwdrs transmitted two copies of raw, unsampled events over wide-area transit. In the new model, Logfwdrs send a single copy to centralized receivers, which immediately apply sampling before buffering into Buftee, carrying only this already-compacted stream.

2. Better compression through uniform partitioning: Data at source is fragmented across thousands of individual servers. After centralization, streams are aggregated and partitioned into uniform batches over wider time windows. This structural uniformity allows compression algorithms to achieve dramatically higher compression ratios than Logfwdr transit batches ever could.

Overall, this was a net reduction of 36 GB/s across wide-area networks. We rolled this out initially to two datasets, HTTP analytics and Ready-Analytics, our in-house one-click analytics product.

We’ve been actively migrating more datasets to this load-balanced architecture since the spring.

Sampling from the get-go

Another strategy we employed was further expanding our sampling mechanism so that we pulled critical processing earlier into the pipeline. Sampling was already used in our centralized services, particularly the receivers, easing pressure on downstream systems. We can be more resource efficient if we send less data downstream (without sacrificing data quality).

The solution here was to simply sample in Logfwdr, in addition to maintaining the sampling in centralized receivers. How the sampling algorithm works here, in short, is each dataset has a key that producer teams have chosen to index and sample the data. When sampling, we first shuffle the records for each key to eliminate bias. Then, for each group of records, we select a sample size equal to the square root of the total count of the records. The result is a representative sample, whether sampled once or twice. To produce estimates, we scale calculations against the sample rate. For example, if we sample 10 out of 100 records, the sample rate would be 10/100, and the unbiased estimate of the original count would be 10*10 = 100.

To ensure this approach was working well, we compared the number of rows written to ClickHouse against the estimated sum for total count using a variety of keys across a variety of traffic footprints, so that “least seen” keys to “most seen” keys were captured across the spectrum.

The result is that for keys with more data, the sample rate decreases. However, keys with less data were sampled comparably. Thus, we still kept a representative sample while delivering and storing fewer events. We’re not compromising the quality of data delivered, even when we deliver less in quantity.

If we look at this more closely, using power laws, we can observe that the double-sampled (red) grows at roughly x0.319 v. sampled-once/control (blue) at x0.485. Another way to picture this is, a key that has 100x more data than another key would have stored roughly 10x the number of rows if single-sampled. Now, it will only store roughly 4x the number of rows. Concretely, a total of 11.6 million events is represented by 18k rows in ClickHouse as opposed to 79k. Double sampling attenuates storage of the “most seen” keys, while still retaining the same detail per event for “least seen” keys.

We initially implemented this strategy against three of our top datasets. Every single one at least halved the amount of compressed data we were originally sending on the wire to centralized receivers. That’s 25GB/s altogether, or over 2PB/day.

Aggregating

Cloudflare offers several analytics datasets built on rollups: aggregates of the raw events computed at ingest time. This makes the opposite tradeoff to sampling: rather than answering any question approximately, we answer a fixed set of questions exactly, provided we choose the dimensions and metrics up front.

For example, in the HTTP dataset, we measure the number of unique occurrences of IP addresses during a given minute rather than the individual IPs themselves. Another example is we sum the total number of GET, POST, PUT, etc. requests for a given domain, for that minute, grouped by the HTTP method. None of these computations actually necessitate waiting until the tail-end of the pipeline to start calculating.

Historically, this aggregation occurred towards the end of the pipeline, inside the inserters which read from Buftee and insert into ClickHouse. Decentralizing this aggregation was an opportunity to spread out load and reduce the amount of data we centralize.

Hence, we built an aggregation functionality that is utilized every step of the way, creating repeated opportunities to combine matching partial aggregates as data converges. Much like sampling, records are grouped by a key, which determines which records can be combined. We aggregate on each instance of Logfwdr. We aggregate again after the partially aggregated events reach the centralized receivers, which push these re-aggregated events onto dedicated partitioned buffers. Because these buffers bring together records from multiple receivers, we aggregate another time after they’ve been read in batches by the ClickHouse inserters. Finally, we aggregate in ClickHouse with aggregating table engines.

The first dataset we rolled this out to was for the HTTP traffic. In just this one dataset alone, we dropped from 9+ GB/s to <2 GB/s in compressed bytes traffic. Even though this is currently the highest cardinality dataset, the aggregations on it still gave us an approximate 80% reduction on the wire.

This aggregation feature is powerful for datasets that can collapse easily, especially for use cases like usage metrics where accuracy on the sums and counts is paramount. It also means we can offer producer teams another option to reduce resource usage besides sampling, which we did. Like Ready-Analytics, we created a generic in-house one-click aggregating analytics product, called Ready-Aggregates. As we continue to iterate on this new feature in the pipeline, we expect to see savings continue to mount.

Impact

The starkest proof of this exponential growth is how rapidly traffic growth consumes headroom.

Take Ready-Analytics for example, where two of the three mechanisms, load balancing and sampling techniques, were applied. In mid-May, load balancing dropped traffic by 50%, plunging from ~26 GB/s to ~13 GB/s. Two months later, traffic had already started surging back up to ~20 GB/s. That’s about half of the reduction, erased by organic traffic growth. We then created even more headroom by reducing this dataset’s throughput rate to the single digits, ~8GB/, when sampling rolled out.

Without both interventions, Ready-Analytics alone would have breached 60 GB/s by September. By processing less data in centralized data centers, we also save a significant amount of CPUs and memory. The following graphs show the impact of load-balancing and sampling in Logfwdr on the CPU and memory usage of just the Ready-Analytics receivers: a ~50% reduction, regaining ~750 CPUs and 3.5 TiB of memory.

Across the entire pipeline altogether, from spring to fall, load balancing (~38 GB/s saved), sampling (~25 GB/s saved across top datasets), and aggregating (~7+ GB/s so far), eliminated ~70 GB/s of compressed traffic from our backbone. These cliff drops provide immediate relief.

If we zoom out such that we look at five years from now, the changes made in this year alone have just as much impact as the short-term benefits. We’ve halved the amount of data we’d be processing in another half a decade’s time. The structural and algorithmic optimizations we have and will continue to make are essential to keep hardware demands sustainable.

If you’re interested in helping us solve these challenges at scale, we’re hiring!

GrabMart data for faster disease outbreak detection

Post Syndicated from Grab Tech original https://engineering.grab.com/grabmart-data-for-faster-disease-outbreak-detection

Abstract

Retail purchases can supplement clinical surveillance because changes in demand for some over-the-counter (OTC) products may appear before confirmed case reports. This article describes an early-stage concept for analysing aggregated GrabMart transaction data to identify unusual changes in product demand. The concept is not a deployed system, and it would require validation by public health experts, privacy review, and regulatory approval before any implementation.

Introduction

Public health agencies use sources such as clinical case reports, laboratory results, and hospital records to monitor disease activity. Retail data may offer an additional signal when demand changes across groups of symptom-related products. It cannot establish a diagnosis or replace clinical evidence.

When using indirect signals, we should assess whether they remain relevant to the outcome we want to measure. This includes considering how changes in user behaviour could affect their interpretation. A retail-based signal can experience similar drift, selection bias, and false alarms. Any useful design must therefore combine statistical validation with careful privacy and governance controls.

Background

Syndromic surveillance tracks patterns that may indicate emerging illness before diagnoses are confirmed. Retail surveillance applies this idea to changes in demand for products associated with symptoms, such as fever remedies or cough medicines.

The proposed method groups eligible products into broad symptom classes and measures changes in aggregate demand over time. An anomaly score can indicate that observed demand differs from an expected seasonal pattern. The score is a statistical signal, not an estimate of how many people have a disease.

The design uses the following terms:


Proposed solution

The proposed pipeline would process only transactions that meet documented eligibility rules. It would map eligible SKUs to symptom classes, aggregate counts across approved time periods and geographic areas, and compare each series with an appropriate baseline. Public health experts would review the resulting Early Outbreak Detection Index alongside independent evidence.

The method deliberately excludes identity linkage and individual-level health inference. It also avoids using a single purchase to classify a customer, target an advertisement, adjust an insurance decision, or change access to a product.

Conceptual data flow

Eligible transactions
        |
        v
Reviewed SKU-to-symptom mapping
        |
        v
Aggregate by approved time period and geographic area
        |
        v
Compare with seasonal and historical baselines
        |
        v
Privacy and quality checks
        |
        v
Aggregate signal for authorised public health evaluation

Analysis and validation

Several statistical methods could model expected demand, including seasonal time-series models and spatial scan statistics. Model selection should follow retrospective evaluation against approved public health data. Evaluation should measure sensitivity, false-alert rate, calibration, geographic stability, and performance during seasonal changes.

The system would also need ongoing monitoring. Product catalogues change, purchasing behaviour shifts, promotions affect demand, and access to GrabMart varies across populations and locations. These factors can produce anomalies unrelated to disease activity.

Privacy and governance

Privacy protection starts with data minimisation. The analysis should use only eligible product categories, coarse geographic areas, and aggregate time windows approved for the stated public health purpose. It should not expose raw transactions or personally identifiable information (PII).

The release process could apply minimum-count thresholds and differential privacy (DP), subject to a documented privacy analysis. Privacy specialists would need to set and review any privacy budget. Access controls, retention limits, audit logs, and contractual restrictions would govern any approved data exchange.

An independent review should cover privacy law, health-related inference, fairness, scientific validity, and the risk of harm from false alerts. An authorised public health body, rather than an automated model, should decide whether and how to communicate a possible outbreak.

Potential applications

If research validates the signal and the required approvals are in place, aggregate trends could support:

  • public health research alongside established surveillance sources;
  • operational planning for broad categories of health supplies; and
  • evaluation of whether retail demand contributes useful evidence during an emerging event.

These applications should use aggregate trends only. The signal should not drive personalised medical advice, individual targeting, insurance decisions, or automatic changes to medicine search rankings.

Limitations

Retail demand is an indirect and incomplete measure of illness. Purchases may reflect promotions, weather, media coverage, household stocking, or changes in product availability. GrabMart customers are not representative of the full population, and the available product mix differs by market.

Mapping a product to a symptom class is also uncertain because many products have several uses. Aggregation and privacy controls reduce disclosure risk but can weaken statistical utility. These limitations require local validation and documented thresholds before anyone interprets the index.

Conclusion

Aggregated retail transactions may add a timely signal to public health research, but they cannot replace clinical surveillance. A responsible design must minimise data, prohibit individual health inference, test the model against independent evidence, and place public health experts in control of interpretation and communication.

This concept remains in the early planning phase. No production deployment, measured performance result, or public health integration is claimed.

Join us

Grab is a leading superapp in Southeast Asia, operating across the deliveries, mobility, and digital financial services sectors. Serving over 900 cities in eight Southeast Asian countries: Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam. Grab enables millions of people every day to order food or groceries, send packages, hail a ride or taxi, pay for online purchases or access services such as lending and insurance, all through a single app. We operate supermarkets in Malaysia under Jaya Grocer and Everrise, which enables us to bring the convenience of on-demand grocery delivery to more consumers in the country. As part of our financial services offerings, we also provide digital banking services through GXS Bank in Singapore and GXBank in Malaysia. Grab was founded in 2012 with the mission to drive Southeast Asia forward by creating economic empowerment for everyone. Grab strives to serve a triple bottom line. We aim to simultaneously deliver financial performance for our shareholders and have a positive social impact, which includes economic empowerment for millions of people in the region, while mitigating our environmental footprint.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Building an evidence-grounded agentic security operations harness on Cloudflare

Post Syndicated from Deanna Tran original https://blog.cloudflare.com/agentic-security-operations/

Security alerts rarely arrive one at a time. A single alert can cause a spike across the environment, requiring a human analyst to decide which alerts are related and what they mean. When multiple arrive at the same time, it can quickly overwhelm even a seasoned security analyst. Enter the alert paradox. Now, our built-in, multi-AI-agent security operations harness can handle more of this work at Cloudflare scale.

Our Cloudflare Managed Defense AI agent harness speeds up the process of gathering data, connecting and aggregating detections, and accounting for missing sources while new alerts continue to arrive. To further analyze context, we make use of the OpenAI Daybreak Defense Network and our partnership with Anthropic. Cloudflare uses approved OpenAI Daybreak and Anthropic models, including GPT-5.6 Cyber and Mythos, for deeper model-backed analysis. Initial analysis and scoring is done with Clef, Cloudflare’s open-source decision model.

Collecting evidence to understand what each alert means requires a lot of time. Even in a highly sophisticated Security Information and Event Management (SIEM), too much is still left for a human to review. Human analysts must gather data, connect and aggregate detections, and account for missing sources while new alerts continue to arrive.

Think about every time a human analyst reviews an alert: "Which should we silence? Which action should we take? Which alert should we ignore? Which should we resolve as false positives? Which should we resolve as true positives? Which should trigger our incident team?" We address this predicament with our AI agent strategy. Our approach reduces all of those questions and gives Managed Defense Analysts a quick and consolidated view, directly providing insight into related alerts, admitted evidence, visible gaps, and recommended next steps. The result: cutting back on the time needed to analyze, and creating a hyper focus on actually getting security alerts resolved and mitigations deployed.

Why a single agent fails

Our first prototype showed the limits of one general-purpose agent. We provided the AI agent the whole investigation. It produced useful analysis, but it also hallucinated claims the evidence did not support. Telemetry, detector descriptions, policies, and threat intelligence were flattened into one prompt, which caused their distinct roles to merge together.

We saw three recurring problems with our first single-shot AI agent harness:

  • Context became authority. A detection is a hypothesis, not proof that an exploit succeeded or an attack occurred. A broad AI agent can blur that distinction.
  • Scope drifted. An AI agent can query the wrong account, time range, or source. You can’t rely on a language model prompt to be a boundary.
  • Failure disappeared. If a lookup times out, the result may not distinguish "not checked" from "checked and not found."

To address these challenges we moved evidence collection and scope enforcement into application code, before model analysis begins.

Recon first, inference second

It's tempting to put an AI agent at every step. The front half of our harness has none.

Before we even call inference, deterministic code runs a fixed set of reconnaissance workflows with versioned API calls. It collects the customer's identity, detection history, traffic baseline, enforcement outcome, and network observations. Each piece of data is stored with its source, version, and timestamp.

Cloudflare sees both the request and the action applied to it. That lets the investigation connect the behavior that triggered an alert with both the control that fired and its outcome.

The fixed recon snapshot also makes evaluation reproducible. If AI agents fetch their own data, two runs may disagree because their inputs changed. Here, the same snapshot can be replayed, so differences between specialist AI agents’ findings come from interpretation rather than retrieval.

Filter noise early

Most alerts are not incidents. The same rule often fires repeatedly on a known traffic pattern, and paging Managed Defense Analysts every time makes it easier to miss a real security incident.

We needed a lightweight triage model to compare each alert with its reconnaissance data: Has this event been detected for the customer before? What did Managed Defense Analysts decide previously? Does the traffic look consistent with normal human behavior? Alerts scored with a high likelihood to be false positives skip analysis by the specialist AI agents.

Clef, running on Workers AI, was the perfect fit for this type of fast agentic reasoning. 

Known high-volume noise is deterministically classified as passive when it arrives. It remains available as context but does not enter the active queue.

Specialist AI agents handle the investigation

For alerts that need deeper review, a coordinator AI agent runs four specialist AI agents in parallel:

  • Traffic analysis reviews request behavior, historical changes, and enforcement.
  • Customer context reviews earlier alerts, dispositions, and Managed Defense Analysts’ decisions.
  • Global telemetry compares the activity with privacy-preserving Internet-wide signals.
  • Threat intelligence checks indicators already admitted to the alert or case.

A synthesis AI agent combines their typed findings into one advisory; it can’t fetch new evidence or choose a classification outside the approved vocabulary. Keeping each task narrow makes unsupported claims easier to catch, and recommendations easier to audit.

Global context without customer data

A security tool knows what happened inside the environment it is deployed in, but little about the world beyond it. Cloudflare compares an alert with patterns seen across its global network.

For example, an IP may be targeting one site, scanning thousands of sites, or appearing for the first time. Those patterns carry different weights. To preserve customer privacy, the global telemetry specialist works only with aggregates; it never receives another customer's individual records or identity.

This view combines features from Cloudflare's CDN, WAF, DDoS, Turnstile, Rate Limiting, and Cloudforce One threat intelligence. The synthesis AI agent weighs both global reputation and customer history. This ensures a globally common pattern can still be used on a per-customer basis, but does not automatically imply a widespread campaign for all customers.

History is evidence

Every evaluation is conscious of what came before it: the alert, the pattern, and which customer. The recon dossier records the alert's own track record including how many times this service alert has fired, how many of those were dispositioned as false positives, and what the Managed Defense Analyst concluded. An attack pattern that has been benign every time your Managed Defense Analysts have seen it is a very different object from the first sighting of something new, and the specialist AI agents are told which one they are looking at. Approved background context is retrieved from previous alerts and cases, so yesterday's conclusions are carried into today's decision, instead of being rebuilt from scratch.

Our system aggregates related alerts into a consolidated case. In each case, we store evidence, findings, and recommendations. Our system deterministically joins and correlates this data, but we leave it to a Managed Defense Analyst to confirm the actual scope. Over time, a case can connect network, application, and Zero Trust evidence together, while tracking the source of the evidence for additional context and reference purposes.

From evidence to decision

Before analysis, the system creates a versioned evidence package with the subject, scope, time anchor, admitted evidence, policy versions, sources, and coverage gaps. Specialists must cite items in that package. Application code checks that every citation exists, belongs to the investigation, and supports the attached claim. Invalid findings are corrected or recorded as limitations.

We lean on Clef a second time to score our evidence. Is the collected evidence enough for a decision? Does any of our collected evidence contradict? Based on this evidence, Clef picks from a deterministically reduced list of attack classifications and dispositions.

Cloudflare's developer platform runs this process. Application code on Workers admits evidence and validates results; Workflows coordinates each stage and saves completed work before the next begins, so a failed stage reuses evidence and findings that already passed validation instead of starting over. D1 keeps investigation and advisory state, R2 holds bounded context and evidence artifacts. Case-chat state persists in Durable Objects, uses Flue, and is enriched with AI Search.

Finally, an LLM-powered agent produces an advisory report using terms that Managed Defense Analysts already work with: affected surface, enforcement outcome, relevant controls, and next step. Managed Defense Analysts can inspect evidence, investigate further, revise the recommendation, or group alerts into a case. Application code fixes the customer scope before any model sees results, and gives each specialist only the evidence it needs. The model never receives authority to cross tenant boundaries or act for the Managed Defense Analysts.

Handling incomplete evidence

At network scale, a source will sometimes fail. A comparison may time out, metadata may be missing, or a threat intelligence lookup may return no match. The system keeps evidence already collected and records the gap.

The advisory distinguishes three states:

  • Not checked
  • Checked, with no matching result
  • Checked, with evidence supporting absence

If global telemetry is unavailable, the system can describe what is unusual for the customer but cannot say whether the pattern is widespread. When the evidence is insufficient, it makes no classification or disposition recommendation.

Remediation

A useful recommendation should lead to a solution, rather than a ticket. The advisory might suggest a rate limiting rule for an abusive path, a WAF custom rule for a signature, or a DDoS protection change. For fully managed customers, Managed Defense Analysts can apply the suggested rules; other customers will receive their recommendations in the dashboard and through their chosen alert path.

In the end, the Managed Defense Analyst remains responsible for the decision and any mitigation. Each alert and case includes the evidence behind the AI agent’s recommendation, which empowers the Managed Defense Analyst to reach a conclusion by accepting or updating the AI agent’s advice.

What comes next

Managed Defense Analysts remain responsible for judgment. The AI agent harness handles more of the repetitive work: assembling investigations, connecting related events, and showing the evidence behind each recommendation. Over the next few quarters, we plan to add a Custom Managed level with more flexibility for each organization.

We also plan to explore continuous AI agents that monitor Cloudflare traffic and surface patterns that fixed rules and thresholds may miss.

The early beta is available in Cloudflare Managed Defense for eligible application-security alerts and cases. If you already use Cloudflare WAF, DDoS protection, Magic Transit, or another supported product, talk to your enterprise account team about adding Managed Defense.

Building Git infrastructure for agent-scale development

Post Syndicated from Brian Celenza original https://github.blog/engineering/architecture-optimization/building-git-infrastructure-for-agent-scale-development/


Every day on GitHub, millions of developers build the products their customers rely on, contribute to open source, and pursue personal projects. GitHub’s architecture has changed steadily over the years to support that work and the growing demands of the developers and organizations who depend on it.

Agentic software development is driving the next architectural shift. With developers and agents working concurrently in repositories that receive millions of commits a day, these workloads demand a different Git architecture. We’re rebuilding GitHub’s Git infrastructure to support them. This post explores the demands shaping that work and the design principles behind it.

Today’s highest-volume workloads show the scale we’re building for. The gap between a typical repository and the busiest ones is wider than most people expect. Here’s a rough picture of the monthly repository activity distribution on GitHub from August 2026:

Repository activity climbs sharply at the far end of the distribution. The busiest repository on GitHub saw roughly a billion requests in August.

Beyond these highest-volume workloads, total Git activity on GitHub is also growing rapidly: between September 2025 and August 2026, it increased to more than 2x its previous level, from 218.2 billion events per month to 473.3 billion.

In September alone, developers and agents made 7.38 billion commits on GitHub, more than five times as many as a year earlier.

The repositories at the top of this curve show what agentic development looks like at its leading edge: large engineering teams running busy CI pipelines alongside growing fleets of agents. Supporting these teams means building Git infrastructure for sustained, concurrent reads and writes at a scale few repositories reach today. We’re investing deeply in Git infrastructure to meet the demands of agentic software development and give teams a foundation built for their most ambitious workloads.

Building for this scale means addressing several architectural challenges:

  • Commit turnaround becomes a bottleneck per agent. An agent in a tight loop commits or checkpoints after nearly every action. Its speed is bounded by how fast a single push completes, so latency that a human would never notice becomes the limiting factor.
  • Write throughput demand is increasing by orders of magnitude. Pushes grew 4.9x year over year, from 0.69 billion to 3.35 billion per month. Thousands of agents working on their own branches in one repository produce a sustained write rate that converges on a single point in our architecture.
  • Merges contend on one reference. Trunk-based development, release trains, and merge queues funnel all that work onto a single ref that has to absorb every merge. Pull request merges on GitHub grew to nearly 4x their volume a year ago.
  • Each push multiplies into thousands of reads. For example, CI and code scanning clone or fetch the same branch tip thousands of times per minute, and that fan-out has to be cheap. GitHub Actions alone ran 3.26 billion times in September, more than 4x as many as a year ago.
  • Operations on a repository must continue to be fast. To keep them fast, we continually compact repository data and clean up objects that are no longer needed. Every new write adds to that work, and the cost compounds as volume climbs.

This is why fast clones only solve part of the problem. Reads are relatively easy to scale: add caches, add replicas, and serve the same bytes to more clients. Scaling reads is essential, but these workloads require more than that. Writes are way harder. Every push has to be stored durably and made visible consistently before the next agent or CI job can build on it.

Where today’s architecture meets new demands

The current architecture has served developers well for years. Every repository is stored by Spokes, which keeps a full copy on the local disks of several fileservers, five by default. Those fast local disks let Git operations read native repository data with low latency, and the extra copies provide redundancy while spreading reads across fileservers. When a push updates a reference, a three-phase commit protocol uses a quorum to ensure that CI, the web UI, and API clients see a consistent repository state. That pairing serves a billion repositories today.

However, the mechanism we use for durability is the same one we use for scale. The copies on disk are the source of truth, so adding read capacity means adding another durable replica. Every replica participates in every write, so a push is only as fast as the slowest replica in its set. The net effect: adding replicas to absorb read load makes writes slower.

For most repositories, this tradeoff works well. At the highest activity levels, it becomes a ceiling: adding read replicas adds overhead to writes, losing a replica reduces read capacity, and losing quorum stops writes entirely. To meet agent-first demands, we need to separate durability from scale without losing what teams rely on today.

Built for the busiest, better for everyone

We’re rebuilding the infrastructure while GitHub keeps running. There’s no maintenance window where the world’s code stops moving, and no version of this work where we ask people to change how they build software while we do it.

We’re building for the most demanding workloads on GitHub: an enterprise shipping under strict regulatory requirements, a team landing a change across a repo that builds an operating system, and an organization running thousands of agents against a single codebase. Engineering for that scale raises the floor for everyone. The maintainer reviewing contributions from volunteers across time zones and the student opening their first pull request get the same faster, more resilient foundation.

The new architecture also must preserve the controls teams already operate on. A maintainer needs branch protections and required reviews so an unreviewed change never reaches the default branch. A security team needs audit logs and repository visibility to investigate a suspicious access event. An on-call engineer needs dependable automation and enough observability to understand why a deployment failed.

For the platform to keep serving everyone here while it scales for the busiest workloads, these are our guiding principles:

  • Build on the workflows developers already trust. Teams rely on workflows like branching, review, merge, and history to build, ship, and govern software at scale. Our new infrastructure is designed to support those same workflows at much higher volumes of activity.
  • Put reliability first. We measure every decision against the reliability that developers and organizations require. Confidence in the platform is what lets an engineering organization build automation, ship on a schedule, meet compliance obligations, and understand the software it produces. This work will meaningfully improve throughput and scale, and those gains extend a foundation of trust that’s already there.
  • Keep people in control of their code. If the system isn’t helping the people and organizations who use it, and isn’t under their control, it isn’t worth building. As agents take on more of the work, the people who own the code can still review, understand, and approve it.

The approach

We are building a new GitHub architecture that can scale much more effectively. Our approach centers around core distributed systems design tenets, applied to the concurrency and scale of agentic software development. Our goal is to continue the forward momentum for open-source communities and enterprises around the world who have built their projects with Git and GitHub, while preserving and adapting the features and controls around it to meet the new needs of the agentic era.

Minimize coordination

A repository that receives many pushes must accept and publish updates quickly. Coordination is valuable when it protects correctness, but too much of it limits write throughput and can turn a busy repository into a bottleneck. Our current architecture is tightly coupled in places it doesn’t need to be, which limits our ability to scale across reads and writes without tough trade-offs. We’re redesigning the system to preserve the coordination that Git semantics require and let everything else proceed independently.

  • Coordinate only what needs agreement. The part of a push that truly needs agreement is the reference update itself. Storing the underlying objects, validating object connectivity, and secret scanning are much more work, but most of it can happen in parallel to other writes. That shrinks the critical path of a push to the small step that needs coordination, so the rest of the work no longer delays the acknowledgment.
  • Move maintenance off the serving path. Compaction and garbage collection are among the heaviest work a repository does, and today they run on the same hosts that answer live Git requests. In the new architecture, separate workers handle maintenance directly against durable storage. A busy repository can be optimized continuously in the background without slowing pushes and fetches.

Decouple storage from compute

Today, complete repository copies on local disks serve both as durable storage and as the layer that answers Git requests. Separating the two lets us scale each one independently.

  • Scale reads without adding durable copies. In the new architecture, read capacity comes from lightweight workers that cache data to serve requests. The authoritative copy of the repository lives in a durable storage layer underneath. That way, the platform can absorb large read spikes from CI fan-out, agent fleets, and large clones without adding work to every push.
  • Let each layer do one job. Authoritative repository data lives in Azure Blob Storage, which already provides durability and replication at Azure scale. The compute layer is optimized for throughput at the lowest latency.
  • Recover faster from failures. When storage and compute are coupled, losing a host reduces both capacity and durability, and recovery means rebuilding a full repository copy. When they’re separate, losing a compute worker is closer to a cache miss: a replacement worker can start serving requests right away and fill its cache from durable storage as traffic arrives.
  • Match capacity to demand. Compute workers can be added or removed as traffic changes instead of provisioning for peak load in advance. A repository going through a burst of activity, like a release or a new agent fleet coming online, can get extra capacity for the burst. Once it passes, that capacity goes away.

Together, these tenets allow us to support higher throughput and more concurrent work without abandoning the reliability and controls that our users need.

What comes next

We’re building an architecture designed to provide the highest throughput and reliability available. Reads and writes scale independently, and the system recovers gracefully from failures. In internal benchmarks, it has delivered up to 35 times higher write throughput, with read capacity that scales on its own to meet demand.

As automated development increases the frequency and concurrency of software change, GitHub will evolve its foundations without trading away the governance and control that teams rely on. We’re already putting that foundation in place. In the next post in this series, we’ll dive deeper into our future architecture and the journey that led us there.

The post Building Git infrastructure for agent-scale development appeared first on The GitHub Blog.

Smarter personalization: How property data helps us understand user price sensitivity

Post Syndicated from Grab Tech original https://engineering.grab.com/price-sensitivity-profiling-using-llm

Introduction

Existing systems estimate user price sensitivity primarily from spending behavior or demographic proxies. They do not systematically account for residential property values, which can indicate a user’s financial circumstances. This omission creates three limitations:

  1. Limited property insights: Existing profiles do not account for property values.
  2. One-dimensional profiles: Users with similar spending patterns but different living standards receive the same classification.
  3. Regional variation: Manual classification does not adapt well to differences between property markets.

This invention adds property data to user profiles to produce affluence segments that account for regional property markets. The invention remains unimplemented and is not deployed in any live market.

Background

Property values vary across buildings, neighborhoods, and regions. A useful classification method must account for these differences while processing property records in several formats. The same classification method could support other industries that use affluence segments.

Solution

A four-step method that combines public property data with clustering techniques to classify user affluence was created:

  1. Data collection and enrichment.
  2. Building-level property price estimation.
  3. Property tier classification.
  4. User mapping to affluence tiers.

The method combines external property data, large language model (LLM) enrichment, and cluster-based segmentation. The resulting profiles can inform personalized offers, targeted marketing, and operational planning.

Data gathering and processing

The system collects public property data from external sources. These records include transaction prices, building types, and related attributes in raw text formats. LLMs standardize the records and extract key attributes such as postcode, building address, transaction price, price per square meter, property size, and floor level. This stage produces a structured property-level dataset for analysis and modeling.

Building-level price estimation

Under the proposed method, transaction records for properties within the same building would be aggregated to calculate a weighted average sale price. The weighting would account for transaction recency and data volume, with the aim of reflecting recent market conditions.

When transaction data is limited, the method could apply rules based on comparable properties in the area. It could also evaluate LLM-assisted extraction of contextual signals from appropriately licensed external sources, such as real estate listings. Any LLM-derived signals would require validation against independent reference data before contributing to a property-value estimate.

The invention has not been implemented, deployed, or tested in a live market. Its model and version, validation methodology, error bounds, and operational safeguards remain subjects for future technical evaluation.

Property tier classification

A hierarchical clustering model groups buildings into affluence tiers based on their estimated resale values. The model accounts for regional differences and local market-value distributions across property types and locations. This stage assigns each building to an affluence tier.

User mapping to property tiers

The system maps would use appropriately aggregated geographic signals to associate users with broad property-market segments and assign a corresponding affluence classification.

Potential future applications

This invention presents a conceptual approach for exploring new ways to support personalization, advertising, and operational planning. It has not been implemented, deployed, or tested in a live market. Subject to technical validation and approval from Privacy, Legal, PR, and the relevant product owners, potential applications could include:

  • Personalization: Tailoring promotions, discounts, subscription plans, and recommendations for optional products and services.
  • Advertising: Supporting more relevant connections between advertising content, merchants, and broad audience segments, alongside tailored marketing campaigns.
  • Operational planning: Informing aggregated analysis used to plan and prioritize delivery and transport capacity.

Learnings and conclusion

This invention presents a conceptual approach that combines publicly available property data, LLM-assisted data structuring, building-level value estimation, hierarchical clustering, and contextual tier assignment. It demonstrates how regional property-market context could complement existing signals, while highlighting dependencies on data quality, model accuracy, geographic coverage, privacy, and fairness.

The approach shows potential applications in personalization, advertising, and operational planning, but these are illustrative, not demonstrated outcomes.

Join us

Grab is a leading superapp in Southeast Asia, operating across the deliveries, mobility, and digital financial services sectors. Serving over 900 cities in eight Southeast Asian countries: Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam. Grab enables millions of people every day to order food or groceries, send packages, hail a ride or taxi, pay for online purchases or access services such as lending and insurance, all through a single app. We operate supermarkets in Malaysia under Jaya Grocer and Everrise, which enables us to bring the convenience of on-demand grocery delivery to more consumers in the country. As part of our financial services offerings, we also provide digital banking services through GXS Bank in Singapore and GXBank in Malaysia. Grab was founded in 2012 with the mission to drive Southeast Asia forward by creating economic empowerment for everyone. Grab strives to serve a triple bottom line. We aim to simultaneously deliver financial performance for our shareholders and have a positive social impact, which includes economic empowerment for millions of people in the region, while mitigating our environmental footprint.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Powering AI-led research through simulation

Post Syndicated from Grab Tech original https://engineering.grab.com/powering-ai-led-research-through-simulation

The short story

Consider a Friday evening. A food order arrives from a mall in the city center. One driver is nearby; another is finishing a drop-off and will be available shortly; a second order from the same mall may or may not appear in the next two minutes. Dispatch the nearby driver now, or hold briefly for a batching opportunity? The decision window is short.

A fulfillment marketplace makes these decisions continuously. Each one is small. Across a city, those decisions determine whether your dinner arrives hot and whether a driver’s hour is well spent.

And that is one decision. There are dozens more: how far to look for a driver, when two orders are worth combining, which of three waiting trips gets the one free bike, how long to keep trying before giving up. These decisions interact, and the setting that is right for Friday at seven is wrong for Tuesday at two. Together they define a space of possible strategies far larger than anyone could exhaustively explore.

We sample only about a dozen points in that space each year. Not for want of ideas: implementing each strategy costs weeks of engineering, and a production experiment takes weeks more to judge. Some questions have no production answer at all. Nobody can run last Saturday again with twenty percent fewer drivers. We were never short of compute resources, and never short of data. We were short of attempts.

So we built sim-rs, a simulator that makes each attempt take minutes, and connected agents that run experiments on it.

sim-rs is self-contained: it requires no production services or databases. The dispatch lifecycle runs in one compiled program alongside a separate dispatch service that is spawned locally and operates offline. Historical booking and driver data go in as plain files, together with a configuration describing the strategy to test. Simulated bookings, trips, drivers, and a single metrics report come out. Processing one city-day of marketplace activity takes tens of minutes, from raw input to finished report. One command in, one report out: a workflow as practical for a software agent as for an engineer.

That compact contract is what makes the simulator AI-friendly. Agents can change bounded components, run reproducible experiments, receive verdicts they cannot alter, and help keep both production logic and behavioral models current.

Building blocks

The essential components

To model a marketplace, the simulator needs four core concepts:

  • Bookings: requests to move something (a passenger, a meal, a parcel), represented in one format regardless of the business vertical.
  • Drivers: simulated workers with a location, a shift, a vehicle, and a queue of work.
  • Trips: units assigned to drivers, containing one booking or several batched into a multi-stop route.
  • Ticks: simulated time, advancing in fixed steps. Nobody waits in real time.

At each tick, the simulator runs the following sequence:

  1. Demand arrives. Historical (or synthesized) bookings whose time has come enter the pool.
  2. Supply moves. Drivers come on shift, advance along routes, go idle, and reposition.
  3. Pre-dispatch cancellations are applied. Cancellation models, including survival-analysis models trained on real behavior, determine which bookings leave the pool.
  4. Dispatch happens. Bookings are batched into trips, trips are matched to drivers by an optimization solver, and a recycling step decides, for each trip, whether to send it now, hold it, or split it back into bookings and try again later.
  5. Post-dispatch cancellations are applied. These include passenger and driver cancellations.
  6. Outcomes are recorded. Every booking, trip, and driver outcome is written to the run outputs.

Crucially, this is a closed loop: today’s dispatch decisions change where drivers end up, which changes what’s possible next tick. That feedback produces second-order effects that a static replay, one that scores historical decisions without updating future supply, cannot show. Supply may dry up in a hot zone, or one bad dispatch rule may cascade into a wave of cancellations.

Marketplace simulation tick loop from demand through dispatch to recorded outcomes
Figure 1. Simulator sequence.

That loop is only the mechanism. Making it a lab takes three further properties: configurability; reproducibility and auditability; and reliable comparison.

1. Interchangeable stages. The major dispatch stages are pluggable. Batching, allocation, cancellation, routing, driver movement, and recycling are each exposed through an interface with interchangeable implementations selected by configuration. This turns a fixed pipeline into an experimental platform: the component under study can be swapped while everything around it stays unchanged. The same mechanism determines which marketplace is being simulated. Ride-hailing, food delivery, parcel delivery, or all three sharing one driver pool are configuration choices within the same codebase, not separate simulators.

2. Self-contained runs. Each experiment is a small, portable package containing its configuration files, input data, source revision, metrics report, and detailed outputs. Anyone holding that package can recreate the setup, whether a reviewer, teammate, agent, or the original author six months later. The report identifies the configured components and headline metrics, while the supplementary per-booking, per-trip, and per-driver outputs let reviewers recompute those metrics and investigate unexpected outcomes without relying on separate notes or systems.

3. Experiments inside the simulation. Production marketplaces have experimentation platforms, so our simulator ships with one too. Experimentable fields can define multiple treatment arms assigned through the same time-based switchbacks, spatial splits, or cell-and-hour schemes used in production. Each booking records its resolved arm for traceability. Running these A/B/n comparisons together exposes every arm to the same demand, drivers, marketplace dynamics, noise, and biases. By reproducing both the conditions and assignment design of a marketplace experiment, simulated insights are more likely to translate into effects observed in production.

Automating the research cycle

Agents do two jobs here, and both need the same environment: searching for strategies that beat the incumbent, and keeping the simulator sufficiently faithful for that search to mean something.

Searching for better strategies

We connect agents to that interface through autoresearch, an automated loop that runs the research cycle end to end. An agent proposes a change, implements it in source code, tests it, and acts on the verdict. A candidate survives only if it improves the target metric and passes every required check; otherwise it is rolled back and the loop continues. The objective may be a marketplace outcome such as orders-throughput or a software measure such as execution time. What matters is a repeatable command-and-metric contract that both humans and agents can use.

Automated research loop connecting an agent to the simulator and evaluation checks

The first failure mode we encountered was specification gaming. Given a target and a loophole, an agent may find the shortest path to the number rather than the improvement we intended. Ours discovered that changing fields used by pre-dispatch cancellation could reduce cancellations and raise completion without improving a single dispatch decision. The metric moved; nothing real had improved. Rather than relying on instructions alone, we built four safeguards into the environment:

  • Core data is immutable. Modules under test may change only the state exposed by their interfaces. An attempt to manipulate protected fields fails to compile instead of producing a misleading result.
  • The verdict is computed, not judged. The simulator computes its own metrics, which the agent can read but not redefine. Executable checks apply calibrated tolerance bands, verify equivalent outputs where required, and run the tests. The agent never judges its own work.
  • Changes are scoped, checked, and reversible. Each experiment runs on its own branch within a declared writable scope, which is checked against the resulting diff. The grading machinery remains outside that scope, regressions cost only a discarded branch, and every surviving change is bounded enough to review in full.
  • Changes are checked at two levels. It first rejects changes that violate type contracts, ownership rules, interface boundaries, or concurrency requirements. The evaluation harness then applies checks suited to the objective: performance work must preserve expected outputs, while strategy experiments must satisfy domain constraints and outcome thresholds.

The speed that matters is the speed of an adaptive research loop, not simulation runtime alone: each iteration uses previous results to propose the next change, then implements, compiles, runs, scores, and decides whether to keep it. The simulator returns a verdict in milliseconds for benchmarks or tens of minutes for a full-day replay, while autoresearch carries each verdict into the next attempt without human handoffs. This turns an overnight run into a connected sequence of evidence-driven experiments, with the safeguards above ensuring that faster iteration compounds reliable evidence rather than mistakes.

One outcome is the familiar purpose of simulation: discovering better marketplace strategies. When asked to explore trip-recycling policy, the loop turned an emerging human intuition into a concrete rule: hold batched orders only as long as service-level deadlines permit, maximizing the chance that another nearby order joins the trip. Because the result is human-readable code, engineers can review, audit, and deploy it like any other pull request.

The same machinery also improves the simulator itself. Over several nights of unattended operation, we aimed the agents at two hot paths in its dispatch logic: the checks that decide which drivers are eligible for a trip, and the pass that adjusts the cost of every driver-and-trip pairing before the solver chooses an assignment. Across roughly 150 logged experiments, three out of four attempts failed to build or were rejected by later gates. The eligibility checks ended up about 10 times faster, and the cost pass about 24 times faster. Because these paths run repeatedly in every replay, improvements compound across subsequent research. Faster and more efficient runs enable testing of more ideas across more markets and dates, repeat runs to separate signal from noise, and validate results more rigorously. Shorter runs also tighten the feedback loop from verdict to next proposal, so improving the instrument accelerates and strengthens every search performed with it.

Execution time is only one possible objective: pointing the same machinery at orders-throughput changes the research question, not the loop itself. Regardless, whatever the objective, the result is only as trustworthy as the simulator behind it. An agent can optimize only the world it is given; if that world has drifted from production, a faster loop will merely produce misleading answers sooner.

Keeping the simulator faithful

A simulator is a claim about the world: that this is how the system behaves and that this is how the people within it respond. Both halves of that claim decay. Production logic changes continuously, while models of passenger and driver behavior grow stale as new product features reshape how people act. A simulator that has drifted from the world produces misleading insights and innovations that fail in production. So the second job we give agents is to keep the simulator faithful.

The system half is a translation problem, and coding agents are particularly good at it. An agent can read a component’s production implementation and implement equivalent logic behind the simulator’s corresponding interface, translating directly from source code rather than from a written description that may already be stale. The result remains a candidate until parity checks show that it matches the production behavior being modeled.

The behavioral half cannot be translated, because no source file tells us how a passenger will behave. It must be inferred from what people actually do. Here, we redirect the same autoresearch loop from dispatch-code optimization to behavioral modeling. It proposes, fits, and scores candidate models, exploring which features predict cancellation and how their effects should be represented. The test is not only how closely a model explains its training data, but also how well it generalizes to held-out data. A model that fits last Tuesday perfectly and next Tuesday poorly does not make the simulator more faithful; it makes the lab more confidently wrong.

The pieces are simple: a realistic marketplace model, swappable parts, repeatable experiments, honest scoring, and an easy way to undo failures. Together, they give agents a safe place to test and improve ideas. Everyone is racing to give AI a bigger brain. We got further by giving it a better lab: a place where it can try a thousand ideas, be wrong cheaply, and receive an honest verdict.

Join us

Grab is Southeast Asia’s leading superapp, serving over 900 cities across eight countries (Cambodia, Indonesia, Malaysia, Myanmar, the Philippines, Singapore, Thailand, and Vietnam). Through a single platform, millions of users access mobility, delivery, and digital financial services, including ride-hailing, food delivery, payments, lending, and digital banking via GXS Bank and GXBank. Founded in 2012, Grab’s mission is to drive Southeast Asia forward by creating economic empowerment for everyone while delivering sustainable financial performance and positive social impact.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, join our team today!

Supporting native Rust in Workers with the new Emscripten target for wasm-bindgen

Post Syndicated from Guy Bedford original https://blog.cloudflare.com/rust-workers-emscripten-target/

Today we’re announcing the first public experimental preview of a feature to better support native Rust code and even Tokio-based applications just running natively on Workers: first-class support for the Emscripten wasm32-unknown-emscripten Rust compiler target on the wasm-bindgen open source toolchain and Cloudflare’s Rust Workers.

wasm-bindgen is the open source toolchain powering Rust-based WebAssembly applications on our V8-based Workers Runtime. Enabling the Emscripten target for wasm-bindgen has been a long-term effort, first initiated by Google over a year ago, and then further reviewed and supported by the Cloudflare engineers maintaining wasm-bindgen.

While still in pre-release, we’re excited to share the new workflow possibilities this work enables in running native wasm-bindgen Rust applications with Emscripten on the web, Node.js, and on Cloudflare’s global Workers platform.

In testing we’ve been able to see significantly improved library compatibility for Rust Workers. To illustrate the sort of capabilities supported, we were able to get a Rust-native Minecraft server (Pumpkin) running inside of a Durable Object with TCP ingress, using real TCP sockets via Tokio. See the end of this post for a full description of this port.

Emscripten is an open-source WebAssembly compiler toolchain initially created by Mozilla and currently maintained by Google engineers, which makes it possible to run and bridge native code with the web platform, including supporting and virtualizing platform features such as timers, file system operations, sockets, and other native functionality.

Since Cloudflare Workers supports Web Platform APIs and Node.js compatibility, we are able to support Emscripten on Workers using its Node.js compilation flags, fully virtualizing native platform features such as timers, file system operations, and sockets on top of our existing Node.js APIs. And with our work on Tokio support, Rust code building on top of Tokio’s async runtime ecosystem can now also be fully integrated into JavaScript-based host environments with this Emscripten target.

We’ve made these current experimental patchsets available with example applications to try out today, including:

Supporting the wasm32-unknown-emscripten target in wasm-bindgen

Mitch Foley on Google’s Portable Toolchains team first encountered the need for Rust WebAssembly toolchains to interoperate with C++ when another internal team at Google was interested in using wasm-bindgen to interface with their JavaScript. The goal was for wasm-bindgen to drive the build and produce the companion JavaScript, while Emscripten’s linker (wasm-ld) would be able to link in any C++ dependencies needed.

Internally, Google uses Emscripten in C++ codebases to generate JavaScript along with the rest of their applications, allowing the C++ and JS to interact with one another. While Emscripten was capable of linking in Rust code as a dependency, the thing it couldn’t do was provide a robust binding system between Rust and JavaScript like wasm-bindgen does.

The problem was both tools assume they are in charge of loading and interacting with JavaScript and generating the final JS and Wasm output. Because of this conflict, Google internal users would have to commit to using one or the other toolchain and never both, and adding a second set of tooling would have doubled the support surface for Google’s Portable Toolchains team.

Mitch and his colleague Yifan Yang crafted a plan to have them work cooperatively: Emscripten would continue to drive the build, load the Wasm module, and provide the companion JS, while wasm-bindgen would produce a smaller portable version of its JavaScript bindings in a format that could be directly included in Emscripten’s library system.

This wasn’t just a technical problem — both Emscripten and the wasm-bindgen maintainers had to support this plan and be willing to maintain integration tests that depended on the other. With feedback from Google’s Portable Toolchains team, Google’s Wasm Tools team, and Cloudflare engineers, this finally resulted in the required changes landing in both projects.

As a result of these efforts, the wasm-bindgen and Emscripten toolchains now have seamless interoperability under the new -sWASM_BINDGEN configuration:

  1. C++ Emscripten code driven by Emscripten’s compiler can be built against static wasm-bindgen Rust code, fully supporting the wasm-bindgen bindings layer alongside the Emscripten bindings layer.
  2. Rust applications using wasm-bindgen and driven by Rust’s compiler can now be built for the Emscripten target, fully supporting Emscripten’s bindings layer alongside wasm-bindgen’s bindings layer.

See the wasm-bindgen Emscripten documentation page for more information about using this target.

Rust library support for Emscripten

After landing the wasm32-unknown-emscripten target support in wasm-bindgen, early prototypes by Cloudflare engineers demonstrated clear success for supporting this target on Cloudflare Workers. Many libraries worked out of the box, even including low-level systems libraries, since Emscripten already supports the target_family = unix in Rust.

Some low-level systems libraries that were unaware of Emscripten required patching, for example libc, socket2, and Mio. Even for these low-level libraries, patches primarily involved adding the Emscripten target to the existing platform gates, for example to explicitly allow target_os = “emscripten”, in place of Wasm platform gates.

Overall we posted these target support patches fairly infrequently, and they were mostly trivial when needed, with the Rust library maintainers very receptive to reviewing the support.

That said, one of the critical foundational libraries that needed significant support was Tokio.

Tokio support

Cloudflare Workers are single-threaded and hosted within a JS event loop, while Tokio async is designed around blocking operations being supported through threaded parking semantics. The two models are clearly not compatible with each other — a blocking operation such as a pending socket read or epoll wait cannot block the shared JS event loop.

To get around this, we had two options: WebAssembly JavaScript Promise Integration or to modify Tokio to support event loop runtime integration.

To support Tokio building for Emscripten, we have contributed full Tokio support patchsets that are being reviewed upstream, with the first target support patch for wasm32-unknown-emscripten already landed upstream in Tokio. With these patchsets, we’ve been able to fully support both approaches in Cloudflare Workers. In our Rust Workers Tokio examples, these patches are required directly pending further integration upstream.

Supporting JSPI

WebAssembly JavaScript Promise Integration (JSPI) maps directly onto Tokio’s existing parking semantics. This is because JSPI allows a blocking Wasm call to suspend the WebAssembly stack on a synchronous operation and return control to the JS event loop, exactly as one would expect of a park.

But when a new Wasm call is made while an earlier one is suspended, JSPI doesn’t break: it instead supports having a new WebAssembly stack being entered while arbitrary existing stacks are suspended at the same time.

The problem here, though, is that Rust itself isn’t aware that its stack is being switched out from under it. Tokio’s runtime context is tracked via a thread local, but a JSPI stack switch is not a thread switch, so the suspended and new stack still share the same thread-local runtime context. As a result, the Tokio runtime context still thinks it is in the parked context when a new Wasm call enters, and then panics because the runtime is already entered.

Supporting fully reentrant JSPI therefore requires careful thread local handling to split context between JSPI context switches. To support this, the thread-local context itself must be swapped on each JSPI enter, exit, suspend, and resume. In effect this is cooperative time-multiplexed threading, with each suspended stack carrying its own runtime context.

With our pre-release Tokio patchset, we were able to implement and verify this model. Finalizing the design and upstreaming it is ongoing in collaboration with the Tokio and Emscripten teams.

Adding an event loop runtime to Tokio

The other runtime approach is full event loop integration. Event loops are of course a common paradigm in native UI applications, so the idea of supporting an event loop runtime for Tokio was certainly not something completely unfamiliar to the maintainers in discussions we had around the Emscripten target support.

The question was rather how to design an event loop for Tokio in such a way that it could work across native applications (including Windows and macOS), as well as for WebAssembly embeddings in JavaScript hosts.

If we could design a general LocalEventLoop runtime for Tokio, we could solve this problem more generally.

A Tokio runtime does two things in a loop: (1) it polls tasks until nothing is ready, and then (2) it waits. The wait is what makes it a runtime rather than a library: the thread parks inside the I/O driver until a socket becomes readable, a timer expires, or another thread wakes it.

But when the host already has its own event loop, Tokio's loop cannot run inside it without blocking the host's. The way around this is to split Tokio's loop in two with both parts able to integrate with the host: (1) becomes an explicit drive() operation that runs one batch of ready tasks and returns, and (2) is replaced by a wake, so that instead of parking, the runtime tells the host it has work and the host calls drive() when it is ready to.

Our proposed LocalEventLoop design for Tokio is a LocalRuntime whose wait has been replaced by a wake. It is built with a standard std::task::Waker that the host owns, which instead of being used to signal that a future should be polled soon, is used by the Tokio runtime to signal that the runtime itself should be driven soon.

Consider the example of a socket read under a regular Tokio runtime:

This would correspond to the following call diagram:

Instead, with LocalEventLoop we can write:

Here, spawn_local returns immediately, with the host event loop taking responsibility for driving the spawned task to completion via el.drive() calls from the host. When stream data is unavailable, the runtime simply returns, handing back control to the host. Once the socket becomes readable, Tokio uses the host_waker to signal that the runtime needs driving.

This LocalEventLoop flow corresponds to the following call diagram:

Everything that would have unparked a native runtime's thread wakes the host instead: a spawn, a task woken from another thread, a socket becoming readable, a timer expiring. Because a Waker is Send + Sync and carries no execution semantics, its implementation is just a notification to the host's event loop. This makes the contract safe by construction: a wake arriving from another thread, from a host callback, or even during a drive, queues work rather than re-entering the runtime. The drive that follows runs on the owning thread with nothing else on the stack.

The one thing you cannot do is wait. block_on still exists and runs a future as far as ready work carries it, but where a normal runtime would park, LocalEventLoop::block_on panics instead. This is because nothing could wake that future from inside the call since its wait belongs to the host.

With this design, the host event loop is never blocked, and interleaves its own work with Tokio's, one batch at a time. The same architecture embeds into a GTK main loop, a Win32 message pump, or a Cocoa run loop. In addition, any number of these runtimes can co-exist due to their cooperative execution semantics.

Supporting sockets and epoll on Emscripten

With both Tokio runtime integration approaches fleshed out for the Rust Emscripten target, we were then able to support most of the Tokio test suite, with one major subsystem still unsupported — the net feature. This includes its sockets APIs: TCP, UDP, and Unix sockets. The reason for this was that Emscripten only supported poll() and a WebSocket emulation layer, but not epoll_wait(), on which Tokio’s I/O driver is built (via mio).

For Cloudflare Workers, we wanted to be able to fully integrate with our TCP sockets APIs, including upcoming inbound TCP. To do this, we would need to build a bridge between Emscripten’s virtualization layer and our own sockets API layer.

Instead of having to build this bridge ourselves, we realized we already have one: the node:net API we support in our Node.js compatibility layer. Emscripten had an -sNODERAWFS mode to bridge natively into Node.js FS APIs, so the same approach could give us a sockets bridge without Emscripten or Cloudflare Workers needing to implement any custom APIs on either side.

We contributed this work in over 40 pull requests to Emscripten, which is now the –sNODERAWSOCKETS layer compilation option, enabling support for epoll, TCP, UDP, and Unix sockets for Emscripten applications in Node.js — and, because Workers implements the same node:net API, on Workers itself as well.

Under JSPI, Emscripten's epoll_wait() simply suspends the stack until readiness, so Tokio's I/O driver works as on native. For LocalEventLoop, readiness instead had to reach the Waker from a JS callback. To support this, we drafted an Emscripten proposal for a new emscripten_epoll_add_listener API to associate a callback on an epoll’s ready events. The next drive() then collects these events with a zero-timeout epoll_wait(), so Tokio's existing I/O driver can be used unchanged.

Running a Minecraft server on Workers

To test out this new target, the challenge was raised to see if a Minecraft server could be deployed to Workers. Dan Lapid then implemented a Pumpkin Minecraft server running on a Durable Object over a single weekend.

Pumpkin is a Rust Minecraft server built on Tokio and designed for multi-core machines. World generation runs on a dedicated thread pool, while the game tick loop and chunk scheduler each run on their own OS threads.

Inside a Durable Object there is exactly one thread, so getting Pumpkin to run there meant turning those threads into cooperative tasks on the event loop. Leaning on the Tokio integration, the tick loop and chunk scheduler became async tasks and each Rayon job became a Tokio task. World generation then runs on the event loop itself, taking one turn per chunk and interleaving with network I/O and game ticks rather than blocking them.

For persistence, Pumpkin writes its world through ordinary std::fs. Under Emscripten’s -sNODERAWFS option file system calls get forwarded to the node:fs Node.js compatibility layer for Workers. Since this bridge is just JavaScript, it is easy to swap out. Dan’s worker-fs-mount library enables mounting a node:fs-compatible file system with its durable-object-fs backend, which stores files as rows in the Durable Object's SQLite storage. With this integrated, every file Pumpkin saves becomes a row in the object's database, written synchronously and committed with the Durable Object's transaction. Pumpkin itself has no idea it isn't on disk, and a restarted object boots straight from the same world.

Networking needed no changes in Pumpkin either. Each player's connection arrives through Workers TCP ingress at the Worker's connect() handler, which forwards it into the Durable Object. There, handleAsNodeConnection() from cloudflare:node dispatches the socket to a net.Server listening on that port inside the object – a new TCP counterpart of handleAsNodeRequest(). Emscripten’s -sNODERAWSOCKETS backend implements TcpListener on top of net.Server, so the server accepts players exactly as it would on Linux, and the returned promise tells the object when the last player has left, so it can save and shut down.

Running a fully persistent Minecraft server inside a Durable Object with multiplayer support demonstrates the level of native compatibility that is possible with this new Emscripten target. We’re excited to see what native Rust applications you can bring to the platform.

Try it out

We’re making these full patchsets and workflows available today for experimental use. Improving wasm-bindgen’s support for modern WebAssembly standards for all users is part of our ongoing commitment to the Rust and Wasm ecosystem.

We welcome all contributions and feedback — find us on GitHub and in the #rust-on-workers channel on Cloudflare’s Discord.