Cloud Engineer: Designing Alphabetical Sort Keys & HMAC-Signed Cursor Pagination in AWS DynamoDB
Unlike relational databases that support arbitrary ORDER BY LOWER(name) ASC LIMIT 25 OFFSET 100 queries, AWS DynamoDB only sorts items lexicographically by the raw UTF-8 byte order of a table's Sort Key (`SK`) or Global Secondary Index (`GSI`). If you store mixed-case product titles directly in a sort key or expose raw `LastEvaluatedKey` JSON maps to browser clients, users experience broken alphabetical ordering (`"Zebra"` sorting before `"apple"`) and attackers can tamper with pagination tokens to enumerate other tenants' keys. As a Cloud Engineer and Backend Engineer, I design normalized lexicographical sort keys and HMAC-authenticated cursor pagination in DynamoDB.
1. Case-Folded, Tie-Broken Composite Sort Keys (`GSI1SK`)
Because DynamoDB requires the primary key (`PK` + `SK`) to be unique, and multiple items within a tenant catalog may share the same alphabetical name, we construct `GSI1SK` by concatenating the NFKC-normalized, case-folded title with the immutable item UUID as a deterministic tie-breaker:
import base64
import hashlib
import hmac
import json
import unicodedata
def build_alphabetical_gsi_keys(tenant_id: str, display_name: str, item_id: str) -> dict[str, str]:
normalized_name = unicodedata.normalize("NFKC", display_name).strip().casefold()
return {
"GSI1PK": f"TENANT#{tenant_id}#CATALOG",
"GSI1SK": f"NAME#{normalized_name}#ID#{item_id}",
}
def encode_signed_cursor(last_evaluated_key: dict, tenant_id: str, secret: bytes) -> str:
payload = json.dumps(last_evaluated_key, sort_keys=True, separators=(",", ":")).encode("utf-8")
mac = hmac.new(secret, f"{tenant_id}:".encode("utf-8") + payload, hashlib.sha256).digest()
token_blob = json.dumps({
"k": base64.urlsafe_b64encode(payload).decode("ascii"),
"s": base64.urlsafe_b64encode(mac).decode("ascii"),
}).encode("utf-8")
return base64.urlsafe_b64encode(token_blob).decode("ascii")
def decode_signed_cursor(cursor: str, tenant_id: str, secret: bytes) -> dict:
outer = json.loads(base64.urlsafe_b64decode(cursor.encode("ascii")))
payload = base64.urlsafe_b64decode(outer["k"].encode("ascii"))
sig = base64.urlsafe_b64decode(outer["s"].encode("ascii"))
expected_mac = hmac.new(secret, f"{tenant_id}:".encode("utf-8") + payload, hashlib.sha256).digest()
if not hmac.compare_digest(sig, expected_mac):
raise ValueError("Invalid or tampered DynamoDB pagination cursor")
return json.loads(payload.decode("utf-8"))
2. Constant-Time Keyset Pagination vs. Offset Scans
Whether a customer is viewing page 1 or page 5,000 of an alphabetical component directory, querying IndexName="GSI1" with ExclusiveStartKey=decode_signed_cursor(...) reads at most Limit=25 items in under 4 ms and consumes a fixed fraction of a Read Capacity Unit (RCU). Pair this pattern with our DynamoDB, Cloud Datastore & Firestore scaling blueprint and DynamoDB WCU cost optimization guide.
Need a Cloud Engineer to design high-performance AWS DynamoDB single-table schemas and GSI pagination? Book a 1-Day Engineering Sprint.