Articles / Security

  • go
  • argon2
  • password-hashing
  • denial-of-service
  • memory
  • authentication

Why a 64 MiB Argon2 Setting Can Take Your Login Server Down

64 MiB sounds tiny, but Argon2 charges it for every password being hashed at that moment. One hundred simultaneous logins want 6,400 MiB. If your container is allowed 512 MiB, the kernel's OOM killer gets a say long before your error handling does.

The setting itself is respectable. RFC 9106 gives Argon2id with 64 MiB, three passes and four lanes as its second recommended option, for memory-constrained environments. "Constrained" there does not mean "multiply by however many strangers press Enter at once".

What 100 logins at once actually cost

I ran 100 hashes through golang.org/x/crypto/argon2 (v0.59.0, Go 1.27.4, 4 CPUs), using a buffered channel to limit how many ran together. Peak resident memory is VmHWM from /proc/self/status.

argon2.IDKey(password, salt, 3, 64*1024, 4, 32) // memory is in KiB
100 hashes, at most N at once

N      peak RSS (approx.)    total time
1      133 MiB               3.6 s
2      261 MiB               3.6 s
4      518 MiB               3.5 to 3.7 s
8      1.0 to 1.2 GiB        3.9 to 4.1 s
100    6.3 GiB               8.5 s

Surprisingly, letting everything run at once was more than twice as slow. Going from one slot to four bought essentially no throughput either, just four times the memory.

That follows partly from p=4: a single hash already spreads its work over four goroutines, enough to occupy this machine. These figures come from one box, so measure yours, but "more concurrency" is clearly not free speed.

Quick detour: four lanes do not mean four lots of 64 MiB. The lanes divide one block of memory between them. The m parameter is the total for the hash, while p says how it is carved up.

Why the peak can be double your sum

At the small limits, one slot peaked near 128 MiB, where you might expect 64. Four peaked near 512 MiB against an expected 256.

Each call to IDKey allocates a fresh slice of 1 KiB blocks. When it returns, that slice is garbage, but it stays allocated until the collector deals with it. Meanwhile the next login asks for another one.

With the default GOGC=100, Go's collector lets the heap grow to roughly twice the live data before finishing a cycle. For a server doing back-to-back hashes, budget about 2 x slots x m, plus whatever the rest of the process needs.

The 100-at-once run did not double because it was all one burst, with nearly everything live together. A second burst arriving before collection would be a different matter.

GOMEMLIMIT will not rescue an unbounded handler

The tempting fix is to set GOMEMLIMIT and walk away. I tried 400 MiB:

  • With four slots, peak RSS fell from about 518 MiB to 388 MiB, with more garbage collections and similar total time.
  • With 100 at once, it still reached about 6.1 GiB, ran over a thousand collections and took longer.

This is correct behaviour. GOMEMLIMIT is a soft limit, and a collector cannot free memory that running hashes are still using. It can tidy up between logins, but it cannot refuse one.

Your web server will not refuse one for you either. net/http starts a goroutine per connection and has no idea that this particular handler is expensive. Under a hard cgroup limit, the likely result is an OOM kill, a restart, clients retrying, and the same thing again.

Put a gate in front of the hash

A buffered channel is enough. Give each hash a slot, wait briefly if none is free, then give up.

package login

import (
	"context"
	"crypto/subtle"
	"errors"
	"time"

	"golang.org/x/crypto/argon2"
)

var ErrBusy = errors.New("password hashing is at capacity")

type Hasher struct {
	slots chan struct{}
}

func NewHasher(maxConcurrent int) *Hasher {
	return &Hasher{slots: make(chan struct{}, maxConcurrent)}
}

// Verify waits up to 500ms for a slot, then recomputes and compares.
func (h *Hasher) Verify(ctx context.Context, password, salt, want []byte) (bool, error) {
	ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
	defer cancel()

	select {
	case h.slots <- struct{}{}:
		defer func() { <-h.slots }()
	case <-ctx.Done():
		return false, ErrBusy
	}

	got := argon2.IDKey(password, salt, 3, 64*1024, 4, uint32(len(want)))
	return subtle.ConstantTimeCompare(got, want) == 1, nil
}

Create one Hasher for the whole process. One per request would limit precisely nothing. In the handler, turn ErrBusy into a 503, perhaps with Retry-After. A fast "not now" for some users beats a dead process for all of them.

The parameters are hard-coded to keep the example short, and want must be the 32-byte hash from your database. Real code should read the parameters stored with each hash, and reject malformed or absurd values before calling Argon2.

The paths people forget

Every Argon2 call needs to use the same budget, including:

  • registration and password changes
  • rehashing an old password after a successful login (do not try to take a second slot while holding the first, or a full gate can stall itself)
  • dummy hashes for unknown usernames, which stop response times revealing which accounts exist
  • API keys or recovery codes, if you hash those with Argon2 too

Choosing the number of slots

Work backwards from the memory limit. Suppose the service may use 512 MiB and needs 128 MiB for everything else. That leaves 384 MiB; each 64 MiB slot needs about 128 MiB under the doubling rule, so the ceiling is three.

I would start at one or two and leave headroom. Then load test with more simultaneous requests than slots, checking:

  • peak memory under sustained load, rather than after one login
  • how many requests get a 503
  • latency including the wait for a slot
  • behaviour with the same CPU and memory limits as production

The limit is per process. Replicas in separate containers each need their own budget, and several processes sharing one host or cgroup add together.

If the sums do not work, change m deliberately

The OWASP password storage cheat sheet lists lower-memory Argon2id configurations, including 19 MiB with two passes and one lane. That can be a sensible choice for a small server. It trades security against capacity, so don't just turn the number down until the graphs look pleasant.

Existing hashes also stay as they are when you change your configuration. Verifying a 64 MiB hash still needs 64 MiB, so size the gate for the largest parameters still in your database until those records have been rehashed.

The gate protects memory, but it cannot keep logins available. Someone flooding the endpoint can occupy every slot and make real users receive the 503s. Rate limit before the hash, by source and by account, while taking care that the account limit does not become an easy way to lock somebody out.