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

推荐订阅源

Help Net Security
Help Net Security
S
Schneier on Security
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园_首页
K
Kaspersky official blog
B
Blog
雷峰网
雷峰网
MyScale Blog
MyScale Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Latest news
Latest news
J
Java Code Geeks
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
S
Secure Thoughts
IT之家
IT之家
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
S
Security @ Cisco Blogs
罗磊的独立博客
M
MIT News - Artificial intelligence
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
P
Proofpoint News Feed
博客园 - 聂微东
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
D
DataBreaches.Net
S
SegmentFault 最新的问题
V
Visual Studio Blog
V
V2EX
The Register - Security
The Register - Security
N
News | PayPal Newsroom
aimingoo的专栏
aimingoo的专栏
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
Hacker News: Ask HN
Hacker News: Ask HN
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
Webroot Blog
Webroot Blog
NISL@THU
NISL@THU
D
Darknet – Hacking Tools, Hacker News & Cyber Security

Hacker News

Introducing Claude Opus 4.7 Qwen Studio The Future of Everything is Lies, I Guess: Where Do We Go From Here? GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis Moving a large-scale metrics pipeline from StatsD to OpenTelemetry / Prometheus GitHub - Nightmare-Eclipse/RedSun: The Red Sun vulnerability repository GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - macOS26/Agent: Any AI, replaces Claude Code, Cursor, OpenClaw. Over 18 LLM providers (Claude, OpenAI, Gemini, Ollama, Zai, HF, Qwen) wired into a native Mac app that writes code, builds Xcode projects, bumps versions, manages git, automates Safari, use AppleScript, JS or Accessibility, extend Agent! w/ MCP Servers, run tasks from your iPhone via Messages. YouTube now lets you turn off Shorts I Made a Terminal Pager Burgers | マクドナルド公式 Commands — HackerNews CLI documentation ChatGPT for Excel PiCore - Raspberry Pi Port of Tiny Core Linux Live Nation illegally monopolized ticketing market, jury finds Google Broke Its Promise to Me. Now ICE Has My Data. Founding Engineer at Adaptional | Y Combinator CRISPR takes important step toward silencing Down syndrome’s extra chromosome GitHub - saffron-health/libretto: The AI toolkit for building reliable browser automations US v. Heppner (S.D.N.Y. 2026) no attorney-client privilege for AI chats [pdf] Unexpected €54k billing spike in 13 hours: Firebase browser key without API restrictions used for Gemini requests Retrofitting JIT Compilers into C Interpreters IPv6 – Google The Accursèd Alphabetical Clock Cybersecurity Looks Like Proof of Work Now Fragments: April 14 Cal.com Goes Closed Source: Why AI Security Is Forcing Our Decision | Cal.com - Scheduling Software for Online Bookings Laravel raised money and now injects ads directly into your agent When moving fast, talking is the first thing to break Too much Discussion of the XOR swap trick – Heather Cafe Introduction to Spherical Harmonics for Graphics Programmers The Grand Line Building a Z-Machine in the worst possible language High-Level Rust: Getting 80% of the Benefits with 20% of the Pain GitHub - duguyue100/midnight-captain: Inspired by Midnight Commander, tailored to my taste. How to build a `git diff` driver · Jamie Tanna | Software Engineer Center for Responsible, Decentralized Intelligence at Berkeley The Local Universe’s Expansion Rate Is Clearer Than Ever, but Still Doesn’t Add Up - A new synthesis of astronomical measurements confirms a persistent mismatch that could point to physics beyond current models The air throughout our homes is infused with microplastics. But there are things you can do to breathe less of them The disturbing white paper Red Hat is trying to erase from the internet – OSnews The Future of Everything is Lies, I Guess: Annoyances ‘Abhorrent’: the inside story of the Polymarket gamblers betting millions on war Productive procrastination — Max van IJsselmuiden maps, territory and LMs 447 Terabytes per Square Centimetre at Zero Retention Energy: Non-Volatile Memory at the Atomic Scale on Fluorographane Show HN: Pardonned.com – A searchable database of US Pardons 20 Years on AWS and Never Not My Job The Seasons are Wrong Artemis II crew splashes down near San Diego after historic moon mission We gave an AI a 3 year retail lease in SF and asked it to make a profit | Andon Labs How a dancer with ALS used brainwaves to perform live On filing the corners off my MacBooks Installing every* Firefox extension OpenClaw’s memory is unreliable, and you don’t know when it will break Steve Blank Nowhere Is Safe Chimpanzees in Uganda locked in vicious 'civil war', say researchers watgo - a WebAssembly Toolkit for Go linux/Documentation/process/coding-assistants.rst at master · torvalds/linux GitHub - callumlocke/json-formatter: Makes JSON easy to read. Founding Product Engineer at Bild AI | Y Combinator A compelling title that is cryptic enough to get you to take action on it GitHub - Keychron/Keychron-Keyboards-Hardware-Design: Industrial design files for Keychron keyboards and mice. 100+ models with CAD assets in STEP, DXF, DWG, and PDF. Source-available, with commercial use allowed for original compatible accessories within the license terms. [ANNOUNCE] WireGuardNT v0.11 and WireGuard for Windows v0.6 Released 1D-Chess Helium Is Hard to Replace Cooperative Vectors Introduction | Evolve Keeping a Postgres queue healthy — PlanetScale Our response to the Axios developer tool compromise Do Americans read print books, e-books or audiobooks more? The Zettelkasten Method in Obsidian: A Practical Setup Guide Artemis II Is Competency Porn and We Are Starving For It WeakC4 Flight Viz — Cockpit View A Mexican surveillance giant you’ve never heard of is now watching the U.S. border Surelock: Deadlock-Free Mutexes for Rust RISC-V 101 – what is it and what does it mean for Canonical? | Ubuntu The Problem That Built an Industry How Much Linear Memory Access Is Enough? | Solidean Investigating Split Locks on x86-64 Simplest hash functions Sybilproof reputation mechanisms (2005) [pdf] What is a property? How Complex is my Code? Static code analysis in Kotlin — tools overview Toffoli gates are all you need PGLite evangelism dcmake: a new CMake debugger UI Clojure on Fennel part one: Persistent Data Structures Fragments: April 2 Python Release Python install manager 26.1 The Life and Death of the Book Review - Liberties Introducing Database Traffic Control — PlanetScale Bitcoin miners are losing $19,000 on every BTC produced as difficulty drops 7.8% God sleeps in the minerals Building slogbox Apple Silicon and Virtual Machines: Beating the 2 VM Limit Who was “Not Even Wrong” first? Pokemon Evolution Vs Darwinian Evolution The APL Programming Language Source Code
Counting Fast in Erlang with :counters and :atomics
2026-05-09 · via Hacker News

I’m just back from giving a training at ElixirConf EU about advanced concurrency patterns in Elixir. I love Erlang’s process model to death. But I also love the things that the OTP team shipped in the past few years focused on essentially escaping that model.

Many languages seem to start from mutable, fast data structures and then build concurrency features, thread isolation, all that. Erlang went the opposite direction. Start with concurrency primitives, immutable data, per-process memory. Then, introduce escape hatches that let processes pry into shared areas of memory and (safely!) modify them.

ETS is the one everybody knows and reaches for when needing a form of somewhat-mutable, shared memory space. In recent OTP releases, however, we got a few wonderful additions to our toolbox. We’ll focus on the ones for counting stuff: :atomics and :counters.

:atomics

An atomics array is an off-heap, shared, mutable block of N × 64-bit integers (signed or unsigned). That’s a mouthful. To break it down:

  • Off-heap: it doesn’t live in the heap of a process. It lives in a magical place somewhere in the BEAM.
  • Shared: no process owns it—the BEAM does.
  • Mutable: when you update this lil’ data structure, you actually change the bytes in memory, as opposed to updating Erlang/Elixir data structures (which copies them because they’re immutable).

The “array” part means that whenever you create a “:atomics data structure”, you’re creating an array of nn integers:

Hand-drawn sketch of an array of 64-bit integers

Create such a data structure and mess around with it:

ref = :atomics.new(n, [])

:atomics.add(ref, _index = 1, 23)

# Add in a different process... it's shared anyways.
fn -> :atomics.add(ref, _index = 1, 19) end
|> Task.async()
|> Task.await()

:atomics.get(ref, 1)
#=> 42
Ref = atomics:new(N, []),
atomics:add(Ref, 1, 23),

%% Add in a different process... it's shared anyways.
{_, Ref} = spawn_monitor(fun() -> atomics:add(Ref, 1, 19) end),
receive
  {'DOWN', Ref, process, _Pid, _Reason} ->
    atomics:get(Ref, 1)
end.
%=> 42

Erlang hides what the data looks like under the hood and just returns a ref here. The array itself is a pretty low-level data structure. For example, there’s no overflow check: if you use unsigned integers and try to set one of these numbers to 264+12^{64} + 1, it’ll just wrap around to 11. No specific process owns this data. It is garbage-collected when the last reference to the array is gone.

What :atomics brings to the table is überfast, atomic operations on these integers. These map pretty much directly to CPU instructions, so when I say fast I mean fast.

Adding and getting numbers is not that much fun. What is fun is operations like add_get/3, which lets you atomically add to the number at the given array index and get the updated value:

:atomics.add_get(ref, _index = 1, 10)
#=> 52
atomics:add_get(Ref, 1, 10).
%=> 52

Atomically means that nothing happens between increasing the number and fetching it, so there cannot be a race condition where some other process alters the number before the caller is able to read it back.

Another atomic operation you can do is exchange the value at the given index and get the old value:

:atomics.exchange(ref, _index = 1, 0)
#=> 52
:atomics.get(ref, _index = 1)
#=> 0
atomics:exchange(Ref, 1, 0).
%=> 52
atomics:get(Ref, 1).
%=> 0

Last but not least, a well-known operation often used for synchronization in concurrent environments: Compare-and-swap (CAS). You provide an “expected value” and a “desired value”, and if the integer is equal to the expected then you set it to the desired value—all atomically of course.

:atomics.compare_exchange(ref, _index = 1, _expected = 10, _desired = 42)
#=> 0 (old value)
:atomics.compare_exchange(ref, _index = 1, _expected = 0, _desired = 42)
#=> :ok
:atomics.get(ref, _index = 1)
#=> 42
atomics:compare_exchange(Ref, 1, 10, 42).
%=> 0 (old value)
atomics:compare_exchange(Ref, 1, 0, 42).
%=> :ok
atomics:get(Ref, 1).
%=> 42

:atomics arrays also guarantee sequentially-consistent ordering of operations across different cells in the same array. Say a writer process calls:

:atomics.put(ref, _index = 1, 42)
:atomics.put(ref, _index = 2, 19)
atomics:put(Ref, 1, 42),
atomics:put(Ref, 2, 19).

Then, a reader process will never see the value at the second index but not the value at the first index. This is really about visibility: readers that see an operation are guaranteed to see all the operations that happened before it. Something to take for granted in BEAM-land, right? Well, properties like this is what turns a data structure like this from a simple collection of integers into a powerful synchronization primitive for multithreading and concurrency.

:counters

Pretty close sibling to :atomics, with a smaller API surface and a different memory model. :counters is still an array of 64-bit integers in a separate memory space, but integers can only be signed and there are no atomic primitives (like exchange or CAS).

ref = :counters.new(n, [:write_concurrency])

:counters.add(ref, _index = 1, 23)
:counters.add(ref, _index = 1, 19)

:counters.get(ref, 1)
#=> 42
Ref = counters:new(N, [write_concurrency]),

counters:add(Ref, 1, 23),
counters:add(Ref, 1, 19),

counters:get(Ref, 1).
%=> 42

There’s no atomic way here to write-then-read (what we’d get with :atomics.add_get/3).

Now for the interesting part and the main difference with :atomics: the underlying data structure. Here, the array is made of one integer per scheduler. This means that a single-element counters array is actually fourteen integers on my machine, because:

System.schedulers_online()
#=> 14
erlang:system_info(schedulers_online).
%=> 14

This architecture makes writes extremely fast, because there’s no contention on the same core. Each scheduler keeps its own array of integers and writes are local—they only end up affecting the integer for the scheduler that the write operation is happening on.

Hand-drawn sketch of the architecture of a :counters array, showing the per-scheduler integers

The complexity is shifted to the read side: :counters.get/2 essentially sums up the integers for each scheduler to get the total value.

Hand-drawn sketch of the :counters.get/2 operation, showing the sum of the per-scheduler integers

Setting a counter to a specific value with :counters.put/3 is even more expensive, as the operation consists of resetting each scheduler’s integer to 0 and then adding the new value to just one of them.

With this data structure powering counters, reads are not guaranteed to see all writes in order. A concurrent reader doesn’t see a consistent snapshot of the counter. If write A happens before write B, the returned sum might reflect both, just A, or just B—depending on which per-scheduler cells had landed by the time the read scanned them.

Hand-drawn sketch of how a concurrent reader might see the counter in a different order than the writes that happened

Write operations cannot be lost, and will all be seen at some point, but concurrent readers can only expect eventually-consistent results.

Benchmarks

I ran some benchmarks to get a sense of the performance of each strategy, using ETS as a baseline. ETS provides ets:update_counter/4 which can be used for some of the things that :counters and :atomics can do.

In this particular benchmark, I’m just incrementing a counter by 1 in a loop, with a varying number of concurrent writers to see how things change when concurrency scales up.

Throughput of each strategy as concurrent writers scale up. Both axes are log. Higher is better (= faster).

Specs

These are the specs of the machine I used to run the benchmarks.

Operating System: macOS
CPU Information: Apple M4 Pro
Number of Available Cores: 14
Available memory: 24 GB
Elixir 1.19.2
Erlang 28.1
JIT enabled: true

With one writer, all solutions perform similarly. There’s no contention at the cores level or between Erlang processes.

As writers scale up, things get more interesting. ETS performance goes down significantly once we go above the number of cores on the machine (remember it’s 14 cores in my case). atomics (and counters in [:atomics] mode) perform better than ETS, showing a consistent throughput of operations as writes scale up. counters, expectedly, performs really well. Throughput goes up as we parallelize writes because writers are not fighting each other for shared resources. Up to the point where we reach the number of cores on the machine, throughput increases as we add writers—there’s no contention, so parallelizing helps. After that, performance plateaus and importantly does not degrade.

Conclusion

We explored two interesting data structures on the BEAM: :atomics and :counters. As with most things in our industry, I’ll leave you with this: pick the right tool for the job.

:atomics is what you want when you need real atomic primitives—compare-and-swap, exchange, atomic add-and-get—plus the sequential-consistency guarantees that turn an array of integers into an actual synchronization primitive. For a real-world example, look no further than Broadway, whose rate-limiting functionality is implemented on top of :atomics.

Reach for :counters in [:write_concurrency] mode when you write a lot and read rarely: hit counters, request counters, anything where you just want to bump a number from many processes without those processes ever fighting over the same cache line. ETS still has its place, but for this specific kind of problem these two give you both better numbers and tighter semantics.

What I love about all of this is the philosophy behind it. Erlang designed narrow, well-scoped primitives that act as escape hatches for the process model when needed. These data structures are about as fast as anything you’ll find in any language that does what they do.


Resources: