Quickstart¶
Run fdyno on your machine. A boto3 program then checks writes, queries, conditions, transactions and change streams.
For local tests only. This setup listens on loopback, has no authentication (any access key is accepted) and has no replication. Read Deploy before other hosts can reach it. To run fdyno in a container instead of DynamoDB Local, see Replace DynamoDB Local.
Clone the repository. Install Go 1.27.4, the FoundationDB 7.3 client and server packages and Python 3.
Start the server¶
Terminal 1:
export FDB_CLUSTER_FILE="$(./scripts/fdb-local.sh start)"
go build -o dynodb ./cmd/dynodb
DYNODB_LISTEN_ADDR=127.0.0.1:8000 ./dynodb
The script starts one private FoundationDB process in .tmp/ and prints its
cluster file. To stop it, run
./scripts/fdb-local.sh stop.
In a second terminal, check the process and its FoundationDB connection:
curl -fsS http://127.0.0.1:8000/livez # the process runs
curl -fsS http://127.0.0.1:8000/readyz # FoundationDB answers
Wait until /readyz succeeds before you run boto3.
If /livez succeeds but /readyz fails, run curl without -f to see the
response body:
foundationdb unreachable: make sure that the first terminal exported the cluster file that the script printed. Make sure that FoundationDB still runs.- fdyno stopped at startup with
FoundationDB client library check failed: FoundationDB did not answer in time. Start FoundationDB first, then start fdyno again.
For other readiness failures, see the probe runbook.
Run the workflow¶
Install boto3:
Save the program below as quickstart.py. Both boto3 clients use the loopback
endpoint and the local test key, so you do not need an AWS account. If you
changed the listener port, change ENDPOINT too.
The program creates a table with a unique name and checks every result. If it creates the table, it tries to delete the table at the end, also when a check fails.
Open the complete boto3 workflow
import time
import uuid
import boto3
from botocore.exceptions import ClientError
ENDPOINT = "http://127.0.0.1:8000"
TABLE = f"fdyno-quickstart-{uuid.uuid4().hex[:8]}"
CLIENT = {
"endpoint_url": ENDPOINT,
"region_name": "us-east-1",
"aws_access_key_id": "local",
"aws_secret_access_key": "local",
}
ddb = boto3.client("dynamodb", **CLIENT)
streams = boto3.client("dynamodbstreams", **CLIENT)
created = False
def check(condition, message):
if not condition:
raise RuntimeError(message)
try:
ddb.create_table(
TableName=TABLE,
AttributeDefinitions=[
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"},
],
KeySchema=[
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"},
],
BillingMode="PAY_PER_REQUEST",
StreamSpecification={
"StreamEnabled": True,
"StreamViewType": "NEW_AND_OLD_IMAGES",
},
)
created = True
ddb.get_waiter("table_exists").wait(TableName=TABLE)
table = ddb.describe_table(TableName=TABLE)["Table"]
check(table["TableStatus"] == "ACTIVE", "table did not become ACTIVE")
stream_arn = table.get("LatestStreamArn")
check(stream_arn, "table did not return LatestStreamArn")
description = streams.describe_stream(StreamArn=stream_arn)["StreamDescription"]
check(description["StreamStatus"] == "ENABLED", "stream is not enabled")
check(len(description["Shards"]) == 1, "quickstart expects the default one shard")
shard_id = description["Shards"][0]["ShardId"]
iterator = streams.get_shard_iterator(
StreamArn=stream_arn,
ShardId=shard_id,
ShardIteratorType="LATEST",
)["ShardIterator"]
print("create: ACTIVE, stream enabled")
profile_key = {"pk": {"S": "USER#1"}, "sk": {"S": "PROFILE"}}
ddb.put_item(
TableName=TABLE,
Item={
**profile_key,
"name": {"S": "Ada"},
"login_count": {"N": "1"},
},
ConditionExpression="attribute_not_exists(pk)",
)
profile = ddb.get_item(
TableName=TABLE,
Key=profile_key,
ConsistentRead=True,
).get("Item")
check(profile is not None, "GetItem did not return the profile")
check(profile["name"]["S"] == "Ada", "unexpected profile name")
check(profile["login_count"]["N"] == "1", "unexpected initial count")
print("put/get: Ada, login_count=1")
rows = ddb.query(
TableName=TABLE,
KeyConditionExpression="pk = :pk",
ExpressionAttributeValues={":pk": {"S": "USER#1"}},
ConsistentRead=True,
)["Items"]
check(len(rows) == 1 and rows[0]["sk"]["S"] == "PROFILE", "Query mismatch")
print("query: 1 item in USER#1")
updated = ddb.update_item(
TableName=TABLE,
Key=profile_key,
UpdateExpression="SET login_count = :next",
ConditionExpression="login_count = :expected",
ExpressionAttributeValues={
":expected": {"N": "1"},
":next": {"N": "2"},
},
ReturnValues="ALL_NEW",
)["Attributes"]
check(updated["login_count"]["N"] == "2", "conditional update mismatch")
print("update: login_count=2")
try:
ddb.update_item(
TableName=TABLE,
Key=profile_key,
UpdateExpression="SET login_count = :next",
ConditionExpression="login_count = :stale",
ExpressionAttributeValues={
":stale": {"N": "1"},
":next": {"N": "99"},
},
ReturnValuesOnConditionCheckFailure="ALL_OLD",
)
raise RuntimeError("stale conditional update unexpectedly succeeded")
except ClientError as error:
check(
error.response["Error"]["Code"] == "ConditionalCheckFailedException",
f"unexpected condition error: {error}",
)
check(
error.response["Item"]["login_count"]["N"] == "2",
"condition failure did not return the current item",
)
print("condition: stale value rejected, current value=2")
event_key = {"pk": {"S": "USER#1"}, "sk": {"S": "EVENT#1"}}
ddb.transact_write_items(
ClientRequestToken=str(uuid.uuid4()),
TransactItems=[
{
"Update": {
"TableName": TABLE,
"Key": profile_key,
"UpdateExpression": "SET login_count = :next",
"ConditionExpression": "login_count = :expected",
"ExpressionAttributeValues": {
":expected": {"N": "2"},
":next": {"N": "3"},
},
}
},
{
"Put": {
"TableName": TABLE,
"Item": {**event_key, "kind": {"S": "LOGIN"}},
"ConditionExpression": "attribute_not_exists(pk)",
}
},
],
)
result = ddb.transact_get_items(
TransactItems=[
{"Get": {"TableName": TABLE, "Key": profile_key}},
{"Get": {"TableName": TABLE, "Key": event_key}},
]
)["Responses"]
check(result[0]["Item"]["login_count"]["N"] == "3", "transaction update missing")
check(result[1]["Item"]["kind"]["S"] == "LOGIN", "transaction put missing")
print("transaction: login_count=3 and event=LOGIN")
records = []
deadline = time.monotonic() + 3
while len(records) < 4 and time.monotonic() < deadline:
page = streams.get_records(ShardIterator=iterator, Limit=100)
records.extend(page.get("Records", []))
iterator = page.get("NextShardIterator", iterator)
if len(records) < 4:
time.sleep(0.1)
event_names = [record["eventName"] for record in records]
check(len(event_names) == 4, f"expected 4 stream records, got {event_names}")
check(event_names.count("INSERT") == 2, f"unexpected stream events: {event_names}")
check(event_names.count("MODIFY") == 2, f"unexpected stream events: {event_names}")
print("stream: 4 records (2 INSERT, 2 MODIFY)")
finally:
if created:
ddb.delete_table(TableName=TABLE)
ddb.get_waiter("table_not_exists").wait(TableName=TABLE)
print("cleanup: table deleted")
Run it:
Expected output:
create: ACTIVE, stream enabled
put/get: Ada, login_count=1
query: 1 item in USER#1
update: login_count=2
condition: stale value rejected, current value=2
transaction: login_count=3 and event=LOGIN
stream: 4 records (2 INSERT, 2 MODIFY)
cleanup: table deleted
Replay: the request and response JSON of each Quickstart call, recorded from a real fdyno.
What just happened¶
- Each write ran as one FoundationDB transaction. The stale conditional update failed before its commit and changed nothing.
TransactWriteItemscommitted the profile update, the event, both stream records and the token in one transaction.- Each stream record committed with its item, in commit order.
- fdyno keeps no table data of its own. If you restart fdyno with the same cluster file, your tables are still there.
- The program deletes its test table. The server and the local FoundationDB keep running.
Next steps¶
| Task | Read |
|---|---|
| Design keys and indexes | Data modeling |
| Check your application's actions | Compatibility |
| Retry writes safely | Reliable writes |
| Build a durable consumer | Change streams |
| Run fdyno in production | Deploy |
| Copy an existing table | Migrate from DynamoDB |
How we know: client workflows.