Intermediate5 min read

Zero-Padding Sort Keys in DynamoDB

A DynamoDB String sorts lexicographically, one byte at a time from the left, not numerically. So "10" lands before "2".

Zero-padding every number to one fixed width is how you make string order match numeric order.

Why does "10" sort before "2" in a DynamoDB sort key?

Because DynamoDB compares String sort keys by their UTF-8 bytes. The first bytes differ ("1" against "2"), and "1" is smaller, so "10" comes first.

Pad every number to a fixed width with leading zeros ("2" becomes "0000000002") and byte order matches numeric order.

  • Numbers stored as strings sort like words. "100", "11", "2" is the order you get, not the one you meant.
  • Pick the width once. Size it for the largest value you'll ever store, then add a few digits. Changing it later means re-keying every item.
  • Descending is a read flag. Read with ScanIndexForward: false. Store an inverted value (maxValue - value) only when one key must mix directions, such as score high-to-low with ties oldest first.

How String sort keys compare

Coming from SQL, ORDER BY score DESC over an integer column sorts numerically because the engine knows the column type. DynamoDB knows it too, but only for a Number sort key.

For type String, results are "stored in order of UTF-8 bytes", per the Query API reference.

"9" (0x39) outranks "10" because its first byte beats "1" (0x31). The first differing byte decides; when one string is a prefix of the other, the shorter one sorts first ("1" before "10").

That's the footgun: once a number lives inside a String sort key, every Query that walks the range returns rows in an order that looks scrambled.

Build a leaderboard sort key

Take a seasonal arcade leaderboard. One per season holds every player's run, and you want the top scores first.

Model it with a in a single item collection:

  • leaderboardId (partition key), e.g. SEASON#2026-SPRING.
  • rankKey (sort key), the zero-padded score plus a tiebreaker.

A naive first attempt stores the raw score as a string:

leaderboardIdrankKeyplayerHandle
SEASON#2026-SPRING"9"quickdraw
SEASON#2026-SPRING"10"ace_pilot
SEASON#2026-SPRING"1500"nightowl
SEASON#2026-SPRING"240"bytecrash

A Query on SEASON#2026-SPRING returns them in this byte order: "10", "1500", "240", "9". The 9-point run sits last and the 1500-point run is buried in the middle. Useless for a leaderboard.

Pad to a fixed width

Pick a width wide enough for the largest score you'll ever record, then left-pad with zeros. Say scores cap at ten million: that's eight digits, so use ten for headroom:

leaderboardIdrankKeyplayerHandle
SEASON#2026-SPRING"0000000009"quickdraw
SEASON#2026-SPRING"0000000010"ace_pilot
SEASON#2026-SPRING"0000000240"bytecrash
SEASON#2026-SPRING"0000001500"nightowl

Every key is now the same length, so byte order and numeric order agree. An ascending Query gives 9, 10, 240, 1500.

Treat the width as permanent. An 11-digit value lands among the 10-digit ones by its first digit: "10000000000" sorts after "0000001500" but before "2000000000".

Check score < 10^width in the code that writes the key, and over-provision the width; the cost is a few bytes.

If you already overflowed, or a migration padded only the new rows, re-key the old ones. UpdateItem can't change a key attribute, so each item becomes a Put under the new key plus a Delete of the old one in one TransactWriteItems.

The mutable sort keys guide has the full recipe.

Sort descending

A leaderboard wants the highest score first. Read the padded key with ScanIndexForward: false and you get 1500, 240, 10, 9, at the same cost as an ascending read.

See descending order for the details.

Add a tiebreaker

Two players can tie. A bare padded score collides on the sort key, and the second write replaces the first (same PK + SK). Append a unique suffix so each run is a distinct item:

rankKey = "<paddedScore>#<paddedTimestamp>#<playerId>"

For example "0000001500#1774000000#p_8842" (1774000000 is 2026-03-20 UTC). Pad the timestamp too, or it reintroduces the bug you just fixed.

A descending read reverses the whole key, timestamp included. With the plain score, a tie lists the later run first. That's fine if the newest run should win.

Mixed directions: invert the score

If ties should go to the earlier run (score high-to-low, time low-to-high), one read direction can't serve both segments. Store 9999999999 - score, zero-padded to the same width, keep the timestamp as is, and read ascending:

scoreinverted (9999999999 - score)rankKey
15009999998499"9999998499#1774000000#p_8842"
2409999999759"9999999759#1774000300#p_1207"
109999999989"9999999989#1774000600#p_3315"
99999999990"9999999990#1774000900#p_0420"

Ascending byte order over the inverted value yields the scores high-to-low (1500, 240, 10, 9), and among tied scores the smaller timestamp comes first.

Use this only when the directions mix; for plain high-to-low, the read flag is simpler.

Check it on real data

In DynoTable, you can browse the season leaderboard sorted by the zero-padded rankKey and check that the padded values line the rows up before you ship the widths.

The expression builder builds the KeyConditionExpression for a begins_with read on the String rankKey (for example 00000015, the scores 1500 to 1599).

It doesn't pad values for you, so check the widths in your writer.

Browsing the season leaderboard in DynoTable, sorted by zero-padded rankKey.
Browsing the season leaderboard in DynoTable, sorted by zero-padded rankKey.

Pitfalls to avoid

  • Padding too narrow. The scheme breaks the first time a value overflows the width. Size for the worst case, add digits, and validate in the writer.
  • Inverting when a flag would do. If you only ever read high-to-low, ScanIndexForward: false is all you need.
  • Mixed widths in one collection. Every key sharing a sort range must use the same width. Re-key the old rows rather than padding only new ones.
  • Padding the wrong segment. In a composite key, pad every numeric segment that takes part in ordering: score and timestamp both.

Next steps

Zero-padding is one of the sort-key strategies; pair it with item collections when you overload a key to serve several patterns, and use a precise Query instead of a Scan once the ordering is right.

Try DynoTable to browse a real table and watch your zero-padded sort keys fall into numeric order before you ship the schema.

By Dmitriy · Updated