Skip to content

perf(bin): add an opt-in mimalloc global allocator - #954

Open
parsnips wants to merge 5 commits into
ExtendDB:mainfrom
parsnips:feat/mimalloc-allocator
Open

parsnips wants to merge 5 commits into
ExtendDB:mainfrom
parsnips:feat/mimalloc-allocator

Conversation

@parsnips

@parsnips parsnips commented Nov 11, 2026 •

Copy link
Copy Markdown

What

Adds an opt-in mimalloc feature to the bin crate. With it, mimalloc::MiMalloc is the process's #[global_allocator] in place of the system allocator.

  • crates/bin: optional mimalloc dependency, a mimalloc = ["dep:mimalloc"] feature, and a #[cfg(feature = "mimalloc")] #[global_allocator] in main.rs.
  • Root Cargo.toml: mimalloc = { version = "0.1", default-features = false } in [workspace.dependencies]. The crate's secure feature stays off.
  • docs/adr/0030-optional-mimalloc-allocator.md: the measurements, their method, and why the feature is off by default.
  • docs/manuals/04-quickstart-setup-guide.md: the build command.
  • .github/workflows/clippy.yml: extenddb/mimalloc joins the test-hooks clippy run, so CI builds the feature.

Default builds do not change.

Why

Closes #953

Measured on the PostgreSQL build of main at 9c3fbfb plus this feature only, on glibc 2.36. The load is conditional inserts with unique keys, sent as PutItem with attribute_not_exists and as PartiQL INSERT, with 32 requests in flight:

Operation Allocator Throughput (ops/s), per measurement Server CPU per request (µs)
PutItem glibc malloc 15,092, 15,099, 14,992 257, 257, 251
PutItem mimalloc 15,679, 15,065, 15,415 226, 222, 227
INSERT glibc malloc 14,613, 6,616*, 14,058 297, 319*, 287
INSERT mimalloc 14,909, 14,595, 15,134 259, 263, 253

* The host also ran other work, which disturbed this step.

  • Server CPU for each request fell by about 12% for both operations.
  • Throughput rose by about 2% to 4%, which is close to the variation between measurements.
  • In a perf profile under the PutItem load, libc.so.6 took 16% of the server's samples with glibc malloc and 5% with mimalloc.
  • Resident memory: no claim. VmHWM at the end of my measurements was 302 to 351 MiB with glibc malloc and 389 to 418 MiB with mimalloc, after 630,000 to 862,000 inserts. The review measured lower memory with mimalloc after about 500,000 inserts with another client. The ADR gives both sets of figures.

An earlier revision of this description gave figures from a fork build that carried two unrelated write-path changes (28% of CPU in libc.so.6, 8.6% more throughput, 23% less CPU). The figures above replace them.

How the figures were measured

The Method section of the ADR has the full text. In short:

  • Builds: cargo build --release --locked -p extenddb, with and without --features mimalloc, in the rust:1.97-bookworm image with RUSTFLAGS=-Cforce-frame-pointers=yes.
  • Host: AMD Ryzen 9 9900X (12 cores, 24 threads), 32 GB, Linux x86_64. The load generator, the server and PostgreSQL ran on it, with no CPU or memory limit on the containers.
  • One measurement is run-one.sh <glibc|mimalloc> <label> (below): a new postgres:16-alpine container, a new deployment and server process (pools of 20, the default 24 tokio workers), then the load generator for PutItem and for INSERT, each at 1, 8, 32 and 128 requests in flight for 10 seconds. Three measurements of each build, in turns: for i in 1 2 3; do ./run-one.sh glibc glibc-$i; ./run-one.sh mimalloc mimalloc-$i; done.
  • Server CPU per request: utime + stime of the server process from /proc/<pid>/stat, read every 100 ms; the ticks of a 10-second step divided by the requests that the step completed.
  • Peak resident memory: VmHWM from /proc/<pid>/status, read one time after the last step. An earlier revision said "after about 600,000 inserts" and gave kB/1000 as MB. The counts are 630,000 to 862,000 inserts for each measurement, and the figures above are MiB.
  • Profile: LEVELS=32 DUR=40s ./run-one.sh <build> perf-<build>, with perf record -F 999 -g -p <pid> -- sleep 25 started 6 seconds into the PutItem step, then perf report --no-children --sort dso.

The script and the load generator are the ones I ran, with the directory and the names of the test access key changed, and with two options of the load generator that this benchmark does not use removed.

run-one.sh: one measurement
#!/usr/bin/env bash
# usage: run2.sh <glibc|mimalloc> <label>
# One measurement: fresh PostgreSQL, fresh ExtendDB (Debian 12 container), then
# the conditional-insert load harness for PutItem and for PartiQL INSERT.
set -euo pipefail
variant=$1; label=$2
B=${BENCH_DIR:?the directory with out/extenddb-glibc, out/extenddb-mimalloc and out/extenddb-load}
out=$B/results/$label; rm -rf $out; mkdir -p $out/home
PGPORT=35432; PORT=28443
LEVELS=${LEVELS:-1,8,32,128}; DUR=${DUR:-10s}
docker rm -f mmbench-pg mmbench-edb >/dev/null 2>&1 || true
docker run -d --name mmbench-pg --shm-size 2g -p 127.0.0.1:$PGPORT:5432 \
  -e POSTGRES_PASSWORD=pg -e POSTGRES_INITDB_ARGS=--no-sync postgres:16-alpine \
  postgres -c max_connections=400 -c fsync=off -c synchronous_commit=off -c full_page_writes=off \
  -c checkpoint_timeout=1h -c max_wal_size=2GB -c shared_buffers=2GB -c effective_cache_size=6GB \
  -c work_mem=64MB -c maintenance_work_mem=512MB -c wal_buffers=64MB >/dev/null
for i in $(seq 1 60); do docker exec mmbench-pg pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1 && break; sleep 1; done
sleep 2
docker run -d --name mmbench-edb --network host -e HOME=/work -w /work \
  -e EXTENDDB_ADMIN_USER=admin -e EXTENDDB_ADMIN_PASSWORD='extenddbAdminLocalDev1!' \
  -v $out/home:/work -v $B/out/extenddb-$variant:/usr/local/bin/extenddb:ro \
  debian:bookworm-slim sleep infinity >/dev/null
x() { docker exec mmbench-edb extenddb "$@"; }
C=/work/extenddb.toml
x init --pg-host 127.0.0.1 --pg-port $PGPORT --pg-user postgres --pg-pass pg \
  --extenddb-user extenddb_app --extenddb-pass extenddbAppLocalDev1 \
  --bind-addr 127.0.0.1 --config $C --overwrite >$out/init.log 2>&1
python3 - $out/home/extenddb.toml $PORT <<'P'
import sys,re
p,port=sys.argv[1],sys.argv[2]; s=open(p).read()
s=s.replace('[server]\n','[server]\nport = '+port+'\n',1)
s=s.replace('[storage.postgres]\n','[storage.postgres]\npool_size = 20\ncatalog_pool_size = 20\n',1)
open(p,'w').write(s)
P
x serve --config $C >$out/serve.log 2>&1
for i in $(seq 1 60); do (echo > /dev/tcp/127.0.0.1/$PORT) 2>/dev/null && break; sleep 1; done
for kv in control_plane_delay_seconds=0 gsi_propagation_delay_ms=0 throttling_enabled=false allow_credential_import=true; do
  x settings --config $C set ${kv%%=*} ${kv##*=} >>$out/setup.log 2>&1
done
m() { x manage --config $C --user admin --password 'extenddbAdminLocalDev1!' "$@" >>$out/setup.log 2>&1; }
m create-account --account-id 000000000000 --account-name bench
m create-user --account-id 000000000000 --user-name svc --user-password 'extenddbSvcLocalDev1!'
m put-user-policy --account-id 000000000000 --user-name svc --policy-name FullAccess \
  --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"dynamodb:*","Resource":"*"}]}'
m import-access-key --account-id 000000000000 --user-name svc --access-key-id AKIAEXTENDDBLOADTEST \
  --secret-access-key extenddbLoadTestSecretAccessKey012345678 --yes
pid=$(for p in $(pgrep -x extenddb); do grep -qs "$out/home\|/work" /proc/$p/cmdline && [ "$(cat /proc/$p/cgroup)" = "$(cat /proc/$(docker inspect -f '{{.State.Pid}}' mmbench-edb)/cgroup)" ] && echo $p; done | head -1)
echo "variant $variant pid $pid mimalloc-symbols $(grep -c -a mi_malloc $B/out/extenddb-$variant || true)" > $out/meta.txt
( while kill -0 $pid 2>/dev/null; do echo "$(date +%s.%N) $(awk '{print $14+$15}' /proc/$pid/stat)"; sleep 0.1; done ) > $out/cpu.txt &
sampler=$!
trap 'kill $sampler 2>/dev/null; docker rm -f mmbench-pg mmbench-edb >/dev/null 2>&1' EXIT
for op in put partiql; do
  $B/out/extenddb-load -endpoint https://127.0.0.1:$PORT -ca $out/home/.extenddb/tls/cert.pem \
    -levels $LEVELS -duration $DUR -op $op 2>&1 | while IFS= read -r l; do echo "$(date +%s.%N) $l"; done > $out/load-$op.txt
done
kill $sampler 2>/dev/null || true
grep -E "VmHWM|VmRSS" /proc/$pid/status >> $out/meta.txt
python3 - $out $DUR $variant <<'P'
import sys,bisect
out,dur,variant=sys.argv[1],float(sys.argv[2].rstrip('s')),sys.argv[3]
c=[(float(a),float(x)) for a,x in (l.split() for l in open(out+'/cpu.txt') if len(l.split())==2)]
ts=[a for a,_ in c]
def ticks(t):
    i=min(max(bisect.bisect_left(ts,t),0),len(c)-1); return c[i][1]
for op in ('put','partiql'):
    for l in open(f'{out}/load-{op}.txt'):
        t,_,rest=l.partition(' '); f=rest.split()
        if len(f)==7 and f[0].isdigit():
            t=float(t); cpu=(ticks(t)-ticks(t-dur))/100
            ops=float(f[1])*dur
            print(f"{variant:9s} {op:8s} conc {int(f[0]):4d}  {float(f[1]):8.0f} ops/s  p50 {f[3]:>6s} p99 {f[4]:>7s} ms  errors {f[6]}  cpu {cpu/dur:5.2f} cores  {cpu/ops*1e6:6.1f} cpu-us/op")
        elif 'error' in rest: print(rest.strip())
P
cat $out/meta.txt
docker rm -f mmbench-pg mmbench-edb >/dev/null 2>&1
load/main.go: the load generator (go build -o out/extenddb-load ./load)
// Load generator for conditional inserts against ExtendDB (or any DynamoDB
// endpoint).
//
// It creates a scratch table, then runs one timed step for each concurrency
// level. Each worker inserts items with unique keys, so no insert conflicts
// with another. For each step it prints the throughput and the client-side
// latency.
//
//	extenddb-load -endpoint https://127.0.0.1:28443 \
//	  -ca /path/to/.extenddb/tls/cert.pem \
//	  -levels 1,8,32,128 -duration 10s -op put
//
// -op put uses PutItem with attribute_not_exists on the partition key.
// -op partiql uses ExecuteStatement with an INSERT statement.
package main

import (
	"context"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"encoding/binary"
	"flag"
	"fmt"
	"net/http"
	"os"
	"slices"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

func fail(format string, args ...any) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
	os.Exit(1)
}

func main() {
	endpoint := flag.String("endpoint", "", "endpoint URL, for example https://127.0.0.1:18443")
	caFile := flag.String("ca", "", "PEM certificate to trust for the endpoint (ExtendDB cert.pem)")
	region := flag.String("region", "us-east-1", "signing region")
	accessKey := flag.String("access-key", "AKIAEXTENDDBLOADTEST", "access key ID")
	secretKey := flag.String("secret-key", "extenddbLoadTestSecretAccessKey012345678", "secret access key")
	levels := flag.String("levels", "1,8,32,128", "comma-separated concurrency levels")
	duration := flag.Duration("duration", 5*time.Second, "time for each level")
	op := flag.String("op", "put", "put (PutItem) or partiql (ExecuteStatement INSERT)")
	valueBytes := flag.Int("value-bytes", 256, "size of the value attribute")
	keep := flag.Bool("keep", false, "do not delete the table at the end")
	flag.Parse()

	if *endpoint == "" {
		fail("-endpoint is required")
	}
	if *op != "put" && *op != "partiql" {
		fail("-op must be put or partiql")
	}
	var concurrency []int
	for _, s := range strings.Split(*levels, ",") {
		n, err := strconv.Atoi(strings.TrimSpace(s))
		if err != nil || n < 1 {
			fail("bad level %q", s)
		}
		concurrency = append(concurrency, n)
	}
	maxConcurrency := slices.Max(concurrency)

	transport := &http.Transport{
		MaxConnsPerHost:     maxConcurrency,
		MaxIdleConns:        maxConcurrency,
		MaxIdleConnsPerHost: maxConcurrency,
	}
	if *caFile != "" {
		pem, err := os.ReadFile(*caFile)
		if err != nil {
			fail("read -ca: %v", err)
		}
		pool := x509.NewCertPool()
		if !pool.AppendCertsFromPEM(pem) {
			fail("-ca has no certificate")
		}
		transport.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}
	}
	client := dynamodb.NewFromConfig(aws.Config{
		Region:           *region,
		BaseEndpoint:     endpoint,
		HTTPClient:       &http.Client{Transport: transport},
		Credentials:      credentials.NewStaticCredentialsProvider(*accessKey, *secretKey, ""),
		RetryMaxAttempts: 1,
	})

	ctx := context.Background()
	// A key-only table: binary hash key a, binary range key b, on-demand.
	input := dynamodb.CreateTableInput{
		BillingMode: types.BillingModePayPerRequest,
		AttributeDefinitions: []types.AttributeDefinition{
			{AttributeName: aws.String("a"), AttributeType: types.ScalarAttributeTypeB},
			{AttributeName: aws.String("b"), AttributeType: types.ScalarAttributeTypeB},
		},
		KeySchema: []types.KeySchemaElement{
			{AttributeName: aws.String("a"), KeyType: types.KeyTypeHash},
			{AttributeName: aws.String("b"), KeyType: types.KeyTypeRange},
		},
	}
	var suffix [4]byte
	_, _ = rand.Read(suffix[:])
	table := fmt.Sprintf("extenddb-load-%x", suffix)
	input.TableName = aws.String(table)
	if _, err := client.CreateTable(ctx, &input); err != nil {
		fail("create table: %v", err)
	}
	if err := dynamodb.NewTableExistsWaiter(client).Wait(ctx, &dynamodb.DescribeTableInput{TableName: &table}, time.Minute); err != nil {
		fail("wait for table: %v", err)
	}
	if !*keep {
		defer func() {
			_, _ = client.DeleteTable(context.Background(), &dynamodb.DeleteTableInput{TableName: &table})
		}()
	}

	value := make([]byte, *valueBytes)
	_, _ = rand.Read(value)
	condition := "attribute_not_exists(#pk)"
	names := map[string]string{"#pk": "a"}
	statement := fmt.Sprintf(`INSERT INTO "%s" VALUE {'%s': ?, '%s': ?, 'v': ?}`, table, "a", "b")

	var sequence atomic.Uint64
	insert := func(ctx context.Context) error {
		// A unique 16-byte partition key for each item.
		var pk [16]byte
		_, _ = rand.Read(pk[:8])
		binary.BigEndian.PutUint64(pk[8:], sequence.Add(1))
		sk := []byte{0}
		if *op == "partiql" {
			_, err := client.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
				Statement: &statement,
				Parameters: []types.AttributeValue{
					&types.AttributeValueMemberB{Value: pk[:]},
					&types.AttributeValueMemberB{Value: sk},
					&types.AttributeValueMemberB{Value: value},
				},
			})
			return err
		}
		item := map[string]types.AttributeValue{
			"a": &types.AttributeValueMemberB{Value: pk[:]},
			"b": &types.AttributeValueMemberB{Value: sk},
			"v": &types.AttributeValueMemberB{Value: value},
		}
		_, err := client.PutItem(ctx, &dynamodb.PutItemInput{
			TableName:                &table,
			Item:                     item,
			ConditionExpression:      &condition,
			ExpressionAttributeNames: names,
		})
		return err
	}

	fmt.Printf("endpoint %s  table %s  op %s  value %d bytes  %v per level\n\n",
		*endpoint, table, *op, *valueBytes, *duration)
	fmt.Printf("%11s %10s %10s %10s %10s %10s %8s\n", "concurrency", "ops/s", "avg ms", "p50 ms", "p99 ms", "max ms", "errors")
	for _, n := range concurrency {
		// Warm the connections, so that the step does not time TLS handshakes.
		var warm sync.WaitGroup
		for range n {
			warm.Go(func() { _ = insert(ctx) })
		}
		warm.Wait()

		stepCtx, cancel := context.WithTimeout(ctx, *duration)
		latencies := make([][]time.Duration, n)
		var errors atomic.Int64
		var firstErr atomic.Pointer[error]
		var wg sync.WaitGroup
		start := time.Now()
		for w := range n {
			wg.Go(func() {
				for stepCtx.Err() == nil {
					t0 := time.Now()
					err := insert(stepCtx)
					if stepCtx.Err() != nil {
						return
					}
					if err != nil {
						errors.Add(1)
						firstErr.CompareAndSwap(nil, &err)
						continue
					}
					latencies[w] = append(latencies[w], time.Since(t0))
				}
			})
		}
		wg.Wait()
		elapsed := time.Since(start)
		cancel()

		var all []time.Duration
		var sum time.Duration
		for _, l := range latencies {
			all = append(all, l...)
			for _, d := range l {
				sum += d
			}
		}
		slices.Sort(all)
		ms := func(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 }
		if len(all) == 0 {
			fmt.Printf("%11d %10s %10s %10s %10s %10s %8d\n", n, "-", "-", "-", "-", "-", errors.Load())
		} else {
			fmt.Printf("%11d %10.0f %10.2f %10.2f %10.2f %10.2f %8d\n",
				n,
				float64(len(all))/elapsed.Seconds(),
				ms(sum/time.Duration(len(all))),
				ms(all[len(all)/2]),
				ms(all[len(all)*99/100]),
				ms(all[len(all)-1]),
				errors.Load())
		}
		if err := firstErr.Load(); err != nil {
			fmt.Printf("            first error: %v\n", *err)
		}
	}
}

load/go.mod:

module extenddb-load

go 1.24

require (
	github.com/aws/aws-sdk-go-v2 v1.47.5
	github.com/aws/aws-sdk-go-v2/credentials v1.20.13
	github.com/aws/aws-sdk-go-v2/service/dynamodb v1.72.3
)

require (
	github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect
	github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect
	github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect
	github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.13.8 // indirect
	github.com/aws/smithy-go v1.28.7 // indirect
)

Testing done

The branch now has main at 44cd436 merged in (6f23c8f), with no conflicts. Cargo.lock is the file of main with the mimalloc and libmimalloc-sys packages added and nothing else: the windows-sys change of winapi-util that an earlier revision carried is gone.

On this host, at 382858d, with toolchain 1.97.0 as in clippy.yml:

cargo fmt --all -- --check                     # clean
cargo clippy --locked --all-targets --features extenddb-storage-cassandra/test-hooks,extenddb-storage-mongodb/test-hooks,extenddb/mimalloc -- -D warnings
                                               # the clippy.yml line; no warnings
cargo test --locked -p extenddb --features mimalloc     # 3 passed
cargo build --locked -p extenddb --features mimalloc    # nm shows mi_malloc_aligned and mi_free (432 mi_ symbols)
cargo build --locked -p extenddb                        # nm shows no mi_ symbol
  • CI at 83320bb, before the merges: all 60 checks passed, among them clippy with the new feature, run-tests on stable and 1.88.0, and the PostgreSQL, SQLite, MongoDB and Cassandra integration jobs. CI has not run at 382858d yet.
  • I did not run cargo test --workspace locally. The library crates and their test binaries do not see the feature, because only the bin crate sets the allocator. CI runs the workspace tests.
  • Benchmark: the table above. Both builds came from this branch's first revision, on main at 9c3fbfb. The changes since then are a code comment, the ADR, the clippy workflow line and the merges of main, so I did not measure again.

Checklist

  • I have read CONTRIBUTING.md
  • All tests pass (cargo test --workspace): in CI at 83320bb; not run locally (see above)
  • Code is formatted (cargo fmt --check)
  • Clippy is clean (cargo clippy -- -W clippy::pedantic): no new warnings in crates/bin; the two there, missing backticks on doc lines 4 and 10 of main.rs, are on main too. The clippy.yml gate with -D warnings passes
  • I have added or updated tests for new functionality: none; a global allocator has no unit-testable behaviour here, and the clippy.yml run builds the feature
  • I have updated documentation if behavior changed
  • Breaking changes are noted below (if any)
  • If this changes the wire protocol, Storage trait, auth model, on-disk
    format, or public CLI surface, an RFC has been accepted or is linked
    below. Otherwise, an ADR captures the decision (link below).

ADR / RFC: ADR-0030. The number 0030 is the next unused one after the index's 0029. Renumber it if 0028 or another number is reserved.

Breaking changes

None. Default builds do not change.


By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.

🤖 Generated with Claude Code

https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the measurements and the ADR. I read the change against main at 9c3fbfb. Default builds do not change, and the allocator applies only to the bin crate. The CI runs for this PR wait for a maintainer to approve them, so no check has run yet.

Comment thread crates/bin/Cargo.toml Resolved
Comment thread crates/bin/src/main.rs Resolved
A new `mimalloc` feature on the bin crate makes mimalloc the global
allocator in place of the system allocator. Default builds do not change.
The clippy workflow builds the feature.

Measured on the PostgreSQL build of main at 9c3fbfb on glibc, under
conditional PutItem and PartiQL INSERT load with 32 requests in flight:
with mimalloc, server CPU for each request fell by about 12% and throughput
rose by about 2% to 4%. Peak resident memory was higher. ADR-0030 records
the measurements and why the feature is off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: michael parsons <michael@twisp.com>
@parsnips
parsnips force-pushed the feat/mimalloc-allocator branch from 82079fe to 83320bb Compare November 11, 2026 05:34
LeeroyHannigan
LeeroyHannigan previously approved these changes Nov 11, 2026

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read 83320bb. The clippy run at clippy.yml:39 now builds extenddb/mimalloc, and the comment in main.rs points at ADR-0030. The ADR now measures main at 9c3fbfb. It reports about 12% less server CPU per request and a throughput change close to the noise. It also reports higher peak resident memory with mimalloc. Clippy, with the new feature run, and Licenses pass at this head.

@LeeroyHannigan
LeeroyHannigan dismissed their stale review November 11, 2026 17:22

I remove my approval.

parsnips and others added 2 commits November 13, 2026 14:02
The ADR index conflicted: main added a License section after the table,
and this branch added the ADR-0030 row. The row goes at the end of the
table, before the License section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: michael parsons <michael@twisp.com>
ExtendDB#964 gave every document under docs/ the same License section, with a
second paragraph that says ExtendDB is maintained by AWS and is not
Amazon DynamoDB. ADR-0030 had the first paragraph only. It now has the
same section as ADR-0029.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: michael parsons <michael@twisp.com>

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the changes. You fixed both items from my 11 Nov review. The clippy job now builds the feature (clippy.yml:39), and the comment in main.rs points at the ADR instead of stating the figure. The default build doesn't link mimalloc, with no mi_ symbols in the binary. The feature build passes the bin crate's tests against PostgreSQL 16, and the merge with main is clean.

One change before it merges:

  1. I couldn't reproduce ADR-0030's figures from what it states. It names no load generator, command line, PostgreSQL settings or worker count, and no method for "server CPU per request" or "peak resident memory". "After about 600,000 inserts" also doesn't fit a 10 s window at about 15,000 ops/s. I wrote my own client (32 processes, one SigV4 HTTPS connection each, PostgreSQL 16 on loopback). Other builds shared the host (load average 14 to 36), so I only compared ratios. The CPU result held: server CPU per request fell 13% to 16% for INSERT and 1.5% to 11% for PutItem. The memory result didn't hold at a longer run. Servers with 62,000 to 82,000 inserts ended at 121.0 to 126.5 MB with mimalloc and 92.5 to 100.5 MB with glibc. In a run of about 500,000 inserts per server, mimalloc ended at 221.5 MB and glibc at 231.2 MB. Please add the script and the commands (or name the tool), and say how you read CPU and peak memory. Then reword the memory sentence so it doesn't claim a direction at 600,000 inserts that nobody can check. Keeping only the relative figures, with the host they came from, would also work.

These were already there at my last review, so they aren't conditions for this PR:

  • The ADR says the Linux system allocator is glibc malloc, but the npm packages' Linux binaries are musl builds (npm-build-matrix.yml:43 and :46).
  • docs/adr/README.md says an ADR is Accepted on merge, so ADR-0030 and its index row can say Accepted.
  • MALLOC_ARENA_MAX, which the admin and deployment guides recommend for backups, doesn't bound Rust allocations in a mimalloc build. A sentence in the ADR's Consequences would cover it.
  • Cargo.lock moves winapi-util's windows-sys from 0.48.0 to 0.61.2, which the feature doesn't need.
  • "Applies to the whole process": C libraries such as aws-lc keep the system malloc, because the crate's override feature is off.

parsnips and others added 2 commits November 23, 2026 21:14
No conflicts. Cargo.lock is main's file with the mimalloc and
libmimalloc-sys packages added and nothing else. The earlier lock file of
this branch also moved the windows-sys version of winapi-util, which the
feature does not need; that change is gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P
Signed-off-by: michael parsons <michael@twisp.com>
The review could not reproduce the figures of ADR-0030 from its text.

The ADR now has a Method section: the builds, the host, the PostgreSQL
and server settings, the load generator and its commands, and how server
CPU per request, peak resident memory and the profile were read. The load
generator and the run script are in the description of the pull request.

The memory sentence said "after about 600,000 inserts". VmHWM was read
one time at the end of a measurement of eight steps, after 630,000 to
862,000 inserts, and it is in MiB now. The review measured lower memory
with mimalloc in a longer run, so the ADR gives both sets of figures and
makes no claim about a direction.

Other points from the review:
- The Linux binaries of the npm packages are musl builds, so "the system
  allocator" is not glibc malloc for them. The ADR measured glibc only.
- The global allocator serves Rust allocations. C libraries such as
  AWS-LC keep the system malloc, because the override feature is off.
- MALLOC_ARENA_MAX does not bound Rust allocations in a build with the
  feature.
- The status is Accepted, as docs/adr/README.md says for a merged ADR.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P
Signed-off-by: michael parsons <michael@twisp.com>
@parsnips
parsnips requested a review from demohan as a code owner November 24, 2026 05:28
@parsnips

Copy link
Copy Markdown
Author

Thanks for the review, and for the second set of measurements. The changes are at 382858d.

1. ADR-0030 figures. The ADR has a Method section now: the builds, the host, the PostgreSQL and server settings, the worker count, the load generator and its commands, and how server CPU per request, peak memory and the profile were read. The run script and the source of the load generator are in the PR description.

  • "After about 600,000 inserts" did not fit a 10-second step because it was not one step. VmHWM was read one time, at the end of a measurement of eight 10-second steps on one server process. The counts are 630,000 to 862,000 inserts for each measurement, and the ADR gives them. The memory figures were also kB/1000; they are MiB now.
  • The ADR makes no claim about the direction of resident memory. It gives my figures and yours, and says that they do not agree.

The items that were not conditions:

  • glibc and musl: the Context says which builds use which malloc, and that the ADR measured glibc only. Consequences asks for a musl measurement before the default changes.
  • Status: Accepted, in the ADR and in the index row.
  • MALLOC_ARENA_MAX: a bullet in Consequences.
  • Cargo.lock: it is the file of main with the mimalloc and libmimalloc-sys packages added. The windows-sys change is gone.
  • "Applies to the whole process": the bullet now says that the allocator serves Rust allocations, and that C libraries such as AWS-LC keep the system malloc because the crate's override feature is off.

The branch has main at 44cd436 merged in, with no conflicts. The local checks are in the description. CI has not run at this head.

LeeroyHannigan added a commit that referenced this pull request Nov 24, 2026
ADR-0031 records the stored form: the escape of the item documents, the
refusal of U+0000 in a PostgreSQL key, the MongoDB mark, and migration 13.
0031 is the first number that no open PR claims: #529 and #536 add 0028,
and #954 adds 0030.

- differences-from-dynamodb.md lists the refusal of U+0000 in a key on
  PostgreSQL.
- The upgrade manual's entry is now a v1.1.0 entry. It says what an
  operator sees when the data body fails after the catalog body committed,
  and describes the MongoDB mark. The Current Status paragraph about 1.0.0
  and migrations 1 to 12 is as main has it.
- 04-component-storage.md and the escape module's comment no longer say
  that the key columns hold escaped text. The escape's byte order and
  prefix tests go with that claim. map_json checks a key with needs_escape.

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reran the Method of ADR-0030 at this head (382858d) with the script and the Go load generator from the description. I changed only container names, ports and how the server's PID is found. My host has 16 CPUs, and other builds kept its one-minute load at 17 to 34, so I compared ratios.

  • You fixed the item of my last review. The Method names the builds, the PostgreSQL settings, the pool sizes, the worker count, and the generator with its commands. It also says how to read CPU per request and peak memory. The memory sentence no longer claims a direction.
  • At 32 in flight, server CPU per request for INSERT fell 12.0% with mimalloc (408.5 to 359.6 µs), as the ADR says.
  • For PutItem it fell 6.4% (343.2 to 321.2 µs), and 4.0% to 10.0% per round. That is about half of "about 12%". The sentence and the table are as they were at my last review, where I said the CPU result held, so this isn't a condition. If you want to give the spread, you could add the figures from a second host. Over my two reviews, a 16-core host under other load measured 1.5% to 11% for PutItem and 10% to 16% for INSERT.
  • Peak memory was higher with mimalloc in two pairs and lower in one, which fits the ADR's "no claim".
  • The default release binary has no mi_ symbols. The feature binary has 63 T mi_ symbols, mi_free and mi_malloc_aligned among them, and it still imports the C malloc, as the new bullet says.
  • The other changed sentences match the code and Cargo.lock. They cover the glibc and musl builds, the Accepted status, the override feature, the MALLOC_ARENA_MAX bullet and the two new crates. Both crates are MIT, and the license notices are current for PostgreSQL, MongoDB and Cassandra.

Before it merges, it needs another merge of main. It conflicts in docs/adr/README.md, where main added the row for ADR-0031 (#1449). With both rows kept, 0030 before 0031, the merge builds in release with and without the feature. The bin crate's tests then pass with the feature against PostgreSQL 16.

CI hasn't run at this head yet.

turns the feature on by default. That decision needs measurements from more
workloads (read-heavy, Scan, the other backends), of resident memory in long
runs, and of a musl build.
- `MALLOC_ARENA_MAX` is a setting of glibc malloc. The backup and restore

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the admin guide also describes MALLOC_ARENA_MAX. Its max_concurrent_jobs row (docs/manuals/05-admin-guide.md:160) tells operators to set MALLOC_ARENA_MAX=1, and it sizes hosts under that setting. You could name it here beside the backup and restore manual and the deployment guide.

@navareamol navareamol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I rebuilt this head in release mode with and without the mimalloc feature and ran a conditional insert load against PostgreSQL 16, three runs of each build in turns, 32 requests in flight. I used my own client, so the request rate is not comparable to yours, but server CPU per request is. PutItem went from 549, 551 and 553 microseconds to 518, 510 and 513 (6 to 7 percent lower). PartiQL INSERT went from 605, 606 and 606 to 550, 542 and 544 (9 to 11 percent lower). The ADR and the description say about 12 percent for both. Could you change the sentence to a range, for example 6 to 12 percent depending on the operation, and say that it is for this host? Peak resident memory was higher with mimalloc in all three of my pairs (about 126 to 132 MB against 98 to 101 MB), which fits the ADR's "no claim", but the Consequences section could name the short run direction too.

Other checks passed here. The default release binary has no mimalloc symbols and the feature binary has 63. Cargo.lock adds only the two crates. The quickstart command works from the repository root. The command that the PR adds to clippy.yml passes with warnings as errors on 1.97.0, and I ran it myself because CI has not run at this head.

I will approve once the branch is merged with main (docs/adr/README.md conflicts) and the 12 percent sentence matches the range that was measured.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Opt-in mimalloc global allocator for the server binary

3 participants