惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
G
Google Developers Blog
D
Docker
The GitHub Blog
The GitHub Blog
H
Help Net Security
WordPress大学
WordPress大学
博客园_首页
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
罗磊的独立博客
I
InfoQ
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Visual Studio Blog
Jina AI
Jina AI
J
Java Code Geeks
博客园 - Franky
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
DataBreaches.Net
Google DeepMind News
Google DeepMind News

Lobsters

Lunacy | Red Vice CIFSwitch: a non-universal Linux local root vulnerability RIPE NCC session fixation: poaching logins with an Atlas probe GNOME 2.20 but its Web Components Agentic Search for Context Engineering – Leonie Monigatti Garnix is shutting down [not OC] akashina.tngl.sh/jjc Concerning Emacs (and Jazz) Nitpicking the shell history scene in ‘Tron: Legacy’ What's cooking on SourceHut? Q2 2026 The tenth OpenPGP email summit Package managers that package package managers Clojure on Fennel part three: parsing WordPress at 23 Finding Miscompiles for Fun, Not Profit GitHub - creusot-rs/creusot: Creusot helps you prove your Rust code is correct. Announcing Rust 1.96.0 | Rust Blog A Love Letter to Neovim sqlite AGENTS.md Am I a Bad Friend? CSS vs. JavaScript • Josh W. Comeau Erlang Ecosystem Foundation - Supporting the BEAM community A brief note about slot access cost in Common Lisp Keyboard latency probe Rethinking the GNOME clipboard issues Back to the Building Blocks’ Building Blocks Tech Notes: Theseus: translating win32 to wasm Fast is better than slow Content-addressed Rust builds (or, what kache actually caches) Intent to Prototype: Embedding API
That one time I used Go panics for flow control
Posted on 2026-05-23. · 2026-05-23 · via Lobsters

How our protagonist discovered that a key service that powers our support was absurdly vulnerable to overload, and what we did to fix it.

Part of our support infrastructure at work is an in-memory datastore, that allows us to query our outstanding support work over various dimensions, such as work type, whether it's been put on hold for some reason, etc. It's functionally equivalent to a single table in an SQL database, where you have a single dataset, boolean filters and configurable sorting.

At work, we have an in-memory datastore that powers part of our support infrastructure. Its kind of analgous to having bitmap filters with post-hoc filtering, so any use of sort/limit will sort the entire result set. And the key part here, is that the result sets can be large enough that sorts can take one or two seconds.

And for a bit of context, this service deployment wasn't autoscaled at the time, and upstream services will retry failed requests. Sometimes after a relatively short timeout. Which is fun.

So, one day, this service had more query load than it can handle; and because of the inelasticity, it got overloaded, and queries started to take way longer (like, up to a minute vs. a typical time of up to 1-2s). Unfortunately, because this was an incident, and sometimes the panic sets in, one of my theories was that memory had gotten slower. Which of course was absurd, but under time presssure, incident brain can be very real.

However, as earlier foreshadowed, this service had simply became overloaded, so we not only had slightly higher than average demand, but also failure demand from retries. Most of the time in a Go service, we pass around a context, so that when the caller gives up on us, we can cancel the operation, short-circuit and bail early.

However, when we were able to get a cpu profile and take a look, the vast majority of the CPU time was taken up in the sort phase of the query. In go, none of the sort functions support cancellation (reasonably so, as normally you're either in a batch context, or sorting small enough counts that the time taken isn't significant). So, what to do?

Normally, context cancellation has leaf functions check for an error, and then propagate it via the typical errors-as-values mechanism. However, none of the sort functions (eg: sort.Sortfunc) take a context, or allow returning an error.

Thankfully, Go has another, non-local signalling mechanism for handling errors (eg: if you've dereferenced a nil pointer), in the form of panics. This tends not to be used much for error handling per-se, because the non-local flow control can be harded to reason about, but it can make sense within a single narrowly defined context.

For example, the encoding/json package does this, for example throwing via json.(*encodingState).error(…), and recovering within the scope of the top level json.(*encodingState).marshal(…) function. So no client code actually sees the non-local control flow, and no engineers experience unexpected panics.

So we changed the code from something like this:

func execute(ctx context.Context) (results, error) {
    resultSet := query.filter(someTable)

    slices.SortFunc(resultSet, func(a, b Row) int {
        return query.compare(a, b)
    })
}

To something like this:

type nonLocalCancellation struct {err error}

func execute(ctx context.Context) (results, error) {
    // setup happens here
    resultSet := query.filter(someTable)

    var sortErr error
    defer func() {
        // Ref: https://go.dev/blog/defer-panic-and-recover
        if r := recover(); r != nil {
            if c, ok := r.(nonLocalCancellation); ok {
                sortErr = c.err
            } else {
                panic(r)
            }
        }
    }()

    slices.SortFunc(resultSet, func(a, b Row) int {
        if ctx.Err() != nil {
            panic(nonLocalCancellation{err})
        }
        return query.compare(a, b)
    })

    if sortErr != nil {
        return nil, sortErr
    }

    return resultSet, nil
}

Which, is a lot of messing about (it's an ugly solution to an ugly problem), but does mean if the caller gives up on the query, we don't waste time sorting a result for someone who will never care about it.