Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.6.0+

Amazon DynamoDB: Batch Put and Delete Items with Partial Retries

See more Amazon DynamoDB Examples

Live writes and deletion: submit 29 small PutRequests and one DeleteRequest in batches of at most 25. Each item operation is atomic, but the batch is not. Only UnprocessedItems are resubmitted after a partial HTTP 200. The example also retries explicit whole-batch throttling failures; it stops on ambiguous transport/server errors.

BatchWriteItem cannot update selected attributes or apply conditions. Puts replace matching items; use UpdateItem or transactions when that is unsuitable. No two operations in a batch may target the same item. Requests must also fit within 16 MB, and stored items within 400 KB; counting to 25 alone is insufficient for arbitrary large input. The generated demonstration items are deliberately small.

Retries are bounded to eight attempts per chunk. Exhaustion saves only the current remaining request; later chunks have not been sent. Persist progress in a real job and reconcile ambiguous outcomes before restarting. Replaying an old put can overwrite a newer value.

The item examples use the ExampleItems table from Create a Table, with string partition key PK and string sort key SK. Wait for ACTIVE. DynamoDB AttributeValue JSON uses wrappers such as {"S":"text"}, {"N":"123.45"}, and {"BOOL":true}. Numeric attributes travel as strings; preserve their precision rather than converting them to int or floating point. Names and IDs remain strings.

Uses DynamoDB's regional JSON API: POST to /, application/x-amz-json-1.0, and an operation-specific X-Amz-Target: DynamoDB_20120810... header. The 20120810 API identifier is still current. Chilkat.Rest and AuthAws sign each request with AWS Signature Version 4, service dynamodb. Set the region once; the example builds the matching commercial AWS endpoint. Other AWS partitions use their own endpoint suffixes.

Read current IAM credentials from a private qa_data/aws/dynamodb.json containing string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials and refresh them before expiry. This code explicitly reads the file; it does not discover an AWS profile or refresh credentials automatically. The session token is included in the signed X-Amz-Security-Token query parameter, so keep request URLs and diagnostics private. A Socket explicitly enables TLS certificate verification and is supplied to Rest. Reuse the configured Rest object for subsequent requests.

IAM permissions for the illustrated actions: dynamodb:BatchWriteItem. Limit access to the appropriate table, index, backup, and restore-target resources. Restoring customer-managed-key encrypted data can also require KMS permissions.

Checks transport completion, HTTP 200, and JSON validity separately. DynamoDB errors include __type and message. HTTP 400 can mean throttling, failed conditions, invalid input, or expired credentials. Use bounded exponential backoff with jitter for retryable failures; renew expired credentials. A failed condition requires an application decision, not an automatic retry. For writes with an uncertain outcome, read/reconcile before retrying. Only the explicitly described batch retries are automatic; other writes are not automatically replayed.

BatchWriteItem reference

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the DynamoDB operation.
    let credentials = CkoJsonObject()!
    credentials.strict = true
    success = credentials.loadFile(path: "qa_data/aws/dynamodb.json")
    if success != true {
        print("Could not load private AWS credentials.")
        return
    }

    if (credentials.jsonType(of: "access_key").intValue != 1) || (credentials.string(of: "access_key") == "") {
        print("Missing or invalid access_key.")
        return
    }

    if (credentials.jsonType(of: "secret_key").intValue != 1) || (credentials.string(of: "secret_key") == "") {
        print("Missing or invalid secret_key.")
        return
    }

    //  Set this once to the region containing the table.
    var region: String? = "us-west-2"
    let endpoint = CkoStringBuilder()!
    endpoint.append(value: "dynamodb.")
    endpoint.append(value: region)
    endpoint.append(value: ".amazonaws.com")
    let aws = CkoAuthAws()!
    aws.accessKey = credentials.string(of: "access_key")
    aws.secretKey = credentials.string(of: "secret_key")
    aws.region = region
    aws.serviceName = "dynamodb"
    aws.signatureVersion = 4
    let rest = CkoRest()!
    rest.connectTimeoutMs = 20000
    rest.idleTimeoutMs = 60000
    success = rest.setAuthAws(authProvider: aws)
    if success != true {
        print("Could not configure AWS signing.")
        return
    }

    //  Temporary IAM/STS credentials require their session token on every signed request.
    //  AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
    //  Leave session_token absent or empty only for credentials that do not have one.
    if credentials.hasMember(jsonPath: "session_token") == true {
        if credentials.jsonType(of: "session_token").intValue != 1 {
            print("session_token must be a string.")
            return
        }

        if credentials.string(of: "session_token") != "" {
            success = rest.addQueryParam(name: "X-Amz-Security-Token", value: credentials.string(of: "session_token"))
            if success != true {
                print("Could not set the session-token parameter.")
                return
            }

        }

    }

    //  Supply a Socket to explicitly enable TLS certificate verification.
    let connection = CkoSocket()!
    connection.requireSslCertVerify = true
    connection.maxReadIdleMs = 60000
    connection.maxSendIdleMs = 60000
    success = connection.connect(hostname: endpoint.getAsString(), port: 443, ssl: true, maxWaitMs: 20000)
    if success != true {
        print("TLS connection failed; inspect diagnostics privately.")
        return
    }

    success = rest.useConnection(connection: connection, autoReconnect: true)
    if success != true {
        print("Could not attach the TLS connection.")
        return
    }

    success = rest.addHeader(name: "Content-Type", value: "application/x-amz-json-1.0")
    if success != true {
        print("Could not set the content type.")
        return
    }

    let body = CkoJsonObject()!
    let result = CkoJsonObject()!
    result.strict = true
    let requestBody = CkoStringBuilder()!
    let responseBody = CkoStringBuilder()!
    let errorType = CkoStringBuilder()!
    success = rest.addHeader(name: "X-Amz-Target", value: "DynamoDB_20120810.BatchWriteItem")
    if success != true {
        print("Could not set the DynamoDB operation.")
        return
    }

    let pending = CkoJsonObject()!
    let random = CkoPrng()!
    //  LIVE WRITES: 29 small puts and one delete, split into 25-operation batches.
    //  PutRequest replaces an existing item with the same key; conditions are unavailable.
    let itemId = CkoStringBuilder()!
    var offset: Int = 0
    var totalOperations: Int = 30
    while (offset < totalOperations) {
        body.clear()
        var batchSize: Int = totalOperations - offset
        if batchSize > 25 {
            batchSize = 25
        }

        var i: Int = 0
        while (i < batchSize) {
            body.i = i
            var inputIndex: Int = offset + i
            if inputIndex < 29 {
                itemId.setString(value: "batch-")
                itemId.appendInt(value: inputIndex)
                body.updateString(jsonPath: "RequestItems.ExampleItems[i].PutRequest.Item.PK.S", value: "group-1")
                body.updateString(jsonPath: "RequestItems.ExampleItems[i].PutRequest.Item.SK.S", value: itemId.getAsString())
                body.updateString(jsonPath: "RequestItems.ExampleItems[i].PutRequest.Item.Data.S", value: "Example value")
                body.updateString(jsonPath: "RequestItems.ExampleItems[i].PutRequest.Item.Version.N", value: "1")
            }
            else {
                body.updateString(jsonPath: "RequestItems.ExampleItems[i].DeleteRequest.Key.PK.S", value: "group-1")
                body.updateString(jsonPath: "RequestItems.ExampleItems[i].DeleteRequest.Key.SK.S", value: "batch-delete")
            }

            i = i + 1
        }

        body.updateString(jsonPath: "ReturnConsumedCapacity", value: "TOTAL")
        var attempt: Int = 0
        var delayCap: Int = 100
        var retry: Bool = true
        while (retry == true) {
            attempt = attempt + 1
            retry = false
            requestBody.clear()
            success = body.emitSb(sb: requestBody)
            if success != true {
                print("Could not encode the batch request.")
                return
            }

            success = rest.fullRequestSb(httpVerb: "POST", uriPath: "/", requestBody: requestBody, responseBody: responseBody)
            if success != true {
                print("Batch transport failed; partial progress or the write outcome may be unknown. Reconcile before replay.")
                return
            }

            success = result.loadSb(sb: responseBody)
            if success != true {
                print("Expected a JSON batch response.")
                return
            }

            if rest.responseStatusCode.intValue == 200 {
                if result.hasMember(jsonPath: "UnprocessedItems") == true {
                    if result.jsonType(of: "UnprocessedItems").intValue != 3 {
                        print("Expected UnprocessedItems object.")
                        return
                    }

                    success = result.objectOf2(jsonPath: "UnprocessedItems", jsonObj: pending)
                    if success != true {
                        print("Could not read unprocessed entries.")
                        return
                    }

                    if pending.size.intValue > 0 {
                        //  Retry exactly the unprocessed map; do not resend already completed entries.
                        body.clear()
                        success = body.appendObjectCopy(name: "RequestItems", jsonObj: pending)
                        if success != true {
                            print("Could not prepare remaining requests.")
                            return
                        }

                        body.updateString(jsonPath: "ReturnConsumedCapacity", value: "TOTAL")
                        retry = true
                    }

                }

            }
            else {
                //  These documented batch throttling failures mean the batch could not be processed.
                //  Do not apply this rule to timeouts, HTTP 500, or arbitrary errors.
                errorType.clear()
                if result.jsonType(of: "__type").intValue == 1 {
                    errorType.append(value: result.string(of: "__type"))
                }

                if (rest.responseStatusCode.intValue == 400) && ((errorType.ends(with: "ProvisionedThroughputExceededException", caseSensitive: true) == true) || (errorType.ends(with: "ThrottlingException", caseSensitive: true) == true)) {
                    retry = true
                }
                else {
                    print("Batch failed. HTTP: \(rest.responseStatusCode.intValue); type: \(errorType.getAsString()!)")
                    return
                }

            }

            if retry == true {
                if attempt == 8 {
                    success = body.writeFile(path: "dynamodb-batch-write-pending.json")
                    if success != true {
                        print("Could not save pending work; retain the current request privately.")
                        return
                    }

                    print("Retry limit reached. Incomplete work saved to dynamodb-batch-write-pending.json; later input chunks, if any, were not sent.")
                    return
                }

                //  Full jitter, exponential growth, capped at five seconds.
                var delayMs: Int = random.randomInt(low: 0, high: delayCap).intValue
                connection.sleepMs(millisec: delayMs)
                delayCap = delayCap * 2
                if delayCap > 5000 {
                    delayCap = 5000
                }

            }

        }

        offset = offset + batchSize
        print("Completed input operations: \(offset)")
    }

    print("Batch writes complete.")

}