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

Amazon DynamoDB: Batch Read Items and Retry Unprocessed Keys

See more Amazon DynamoDB Examples

Read three unique keys, correlate unordered results by their primary key, and retry only UnprocessedKeys with bounded exponential backoff and jitter. Missing items are not returned. They are reported as missing only after all unprocessed keys have completed. A repeated unprocessed key is normal and is not treated as a pagination cycle.

BatchGetItem supports at most 100 keys and 16 MB per response; partial results can occur below those limits, including a 1 MB per-partition limit. Split larger inputs into separate batches. This example uses strong reads but the entire batch is not an atomic snapshot. After eight attempts it saves the remaining request privately and reports incomplete work. Applications must also retain already returned items and any input not yet submitted.

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:BatchGetItem. 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.

BatchGetItem reference

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoCredentials
    String sRegion
    Handle hoEndpoint
    Variant vAws
    Handle hoAws
    Handle hoRest
    Variant vConnection
    Handle hoConnection
    Handle hoBody
    Handle hoResult
    Variant vRequestBody
    Handle hoRequestBody
    Variant vResponseBody
    Handle hoResponseBody
    Handle hoErrorType
    Variant vPending
    Handle hoPending
    Handle hoRandom
    Handle hoRequestedIds
    Handle hoFound
    Integer i
    Integer iAttempt
    Integer iDelayCap
    Boolean iRetry
    String sReturnedId
    Integer iDelayMs
    String sTemp1
    Integer iTemp1
    Boolean bTemp1
    Boolean bTemp2

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the DynamoDB operation.
    Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
    If (Not(IsComObjectCreated(hoCredentials))) Begin
        Send CreateComObject of hoCredentials
    End
    Set ComStrict Of hoCredentials To True
    Get ComLoadFile Of hoCredentials "qa_data/aws/dynamodb.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load private AWS credentials."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid access_key."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid secret_key."
        Procedure_Return
    End

    //  Set this once to the region containing the table.
    Move "us-west-2" To sRegion
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "dynamodb." To iSuccess
    Get ComAppend Of hoEndpoint sRegion To iSuccess
    Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
    Get Create (RefClass(cComChilkatAuthAws)) To hoAws
    If (Not(IsComObjectCreated(hoAws))) Begin
        Send CreateComObject of hoAws
    End
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    Set ComAccessKey Of hoAws To sTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Set ComSecretKey Of hoAws To sTemp1
    Set ComRegion Of hoAws To sRegion
    Set ComServiceName Of hoAws To "dynamodb"
    Set ComSignatureVersion Of hoAws To 4
    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Set ComConnectTimeoutMs Of hoRest To 20000
    Set ComIdleTimeoutMs Of hoRest To 60000
    Get pvComObject of hoAws to vAws
    Get ComSetAuthAws Of hoRest vAws To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure AWS signing."
        Procedure_Return
    End

    //  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.
    Get ComHasMember Of hoCredentials "session_token" To bTemp1
    If (bTemp1 = True) Begin
        Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
        If (iTemp1 <> 1) Begin
            Showln "session_token must be a string."
            Procedure_Return
        End

        Get ComStringOf Of hoCredentials "session_token" To sTemp1
        If (sTemp1 <> "") Begin
            Get ComStringOf Of hoCredentials "session_token" To sTemp1
            Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set the session-token parameter."
                Procedure_Return
            End

        End

    End

    //  Supply a Socket to explicitly enable TLS certificate verification.
    Get Create (RefClass(cComChilkatSocket)) To hoConnection
    If (Not(IsComObjectCreated(hoConnection))) Begin
        Send CreateComObject of hoConnection
    End
    Set ComRequireSslCertVerify Of hoConnection To True
    Set ComMaxReadIdleMs Of hoConnection To 60000
    Set ComMaxSendIdleMs Of hoConnection To 60000
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
    If (iSuccess <> True) Begin
        Showln "TLS connection failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get pvComObject of hoConnection to vConnection
    Get ComUseConnection Of hoRest vConnection True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not attach the TLS connection."
        Procedure_Return
    End

    Get ComAddHeader Of hoRest "Content-Type" "application/x-amz-json-1.0" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set the content type."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoBody
    If (Not(IsComObjectCreated(hoBody))) Begin
        Send CreateComObject of hoBody
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Get Create (RefClass(cComChilkatStringBuilder)) To hoRequestBody
    If (Not(IsComObjectCreated(hoRequestBody))) Begin
        Send CreateComObject of hoRequestBody
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoResponseBody
    If (Not(IsComObjectCreated(hoResponseBody))) Begin
        Send CreateComObject of hoResponseBody
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoErrorType
    If (Not(IsComObjectCreated(hoErrorType))) Begin
        Send CreateComObject of hoErrorType
    End
    Get ComAddHeader Of hoRest "X-Amz-Target" "DynamoDB_20120810.BatchGetItem" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set the DynamoDB operation."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoPending
    If (Not(IsComObjectCreated(hoPending))) Begin
        Send CreateComObject of hoPending
    End
    Get Create (RefClass(cComChilkatPrng)) To hoRandom
    If (Not(IsComObjectCreated(hoRandom))) Begin
        Send CreateComObject of hoRandom
    End
    //  Every requested key must be unique. This small example uses one partition.
    Get Create (RefClass(cComChilkatStringTable)) To hoRequestedIds
    If (Not(IsComObjectCreated(hoRequestedIds))) Begin
        Send CreateComObject of hoRequestedIds
    End
    Get ComAppend Of hoRequestedIds "item-001" To iSuccess
    Get ComAppend Of hoRequestedIds "item-002" To iSuccess
    Get ComAppend Of hoRequestedIds "item-003" To iSuccess
    Get Create (RefClass(cComChilkatHashtable)) To hoFound
    If (Not(IsComObjectCreated(hoFound))) Begin
        Send CreateComObject of hoFound
    End
    Move 0 To i
    While (i < (ComCount(hoRequestedIds)))
        Set ComI Of hoBody To i
        Get ComUpdateString Of hoBody "RequestItems.ExampleItems.Keys[i].PK.S" "group-1" To iSuccess
        Get ComStringAt Of hoRequestedIds i To sTemp1
        Get ComUpdateString Of hoBody "RequestItems.ExampleItems.Keys[i].SK.S" sTemp1 To iSuccess
        Move (i + 1) To i
    Loop

    Get ComUpdateBool Of hoBody "RequestItems.ExampleItems.ConsistentRead" True To iSuccess
    Get ComUpdateString Of hoBody "RequestItems.ExampleItems.ProjectionExpression" "#pk, #sk, #data" To iSuccess
    Get ComUpdateString Of hoBody "RequestItems.ExampleItems.ExpressionAttributeNames.#pk" "PK" To iSuccess
    Get ComUpdateString Of hoBody "RequestItems.ExampleItems.ExpressionAttributeNames.#sk" "SK" To iSuccess
    Get ComUpdateString Of hoBody "RequestItems.ExampleItems.ExpressionAttributeNames.#data" "Data" To iSuccess
    Get ComUpdateString Of hoBody "ReturnConsumedCapacity" "TOTAL" To iSuccess
    Move 0 To iAttempt
    Move 100 To iDelayCap
    Move True To iRetry
    While (iRetry = True)
        Move (iAttempt + 1) To iAttempt
        Move False To iRetry
        Send ComClear To hoRequestBody
        Get pvComObject of hoRequestBody to vRequestBody
        Get ComEmitSb Of hoBody vRequestBody To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not encode the batch request."
            Procedure_Return
        End

        Get pvComObject of hoRequestBody to vRequestBody
        Get pvComObject of hoResponseBody to vResponseBody
        Get ComFullRequestSb Of hoRest "POST" "/" vRequestBody vResponseBody To iSuccess
        If (iSuccess <> True) Begin
            Showln "Batch transport failed; partial progress or the write outcome may be unknown. Reconcile before replay."
            Procedure_Return
        End

        Get pvComObject of hoResponseBody to vResponseBody
        Get ComLoadSb Of hoResult vResponseBody To iSuccess
        If (iSuccess <> True) Begin
            Showln "Expected a JSON batch response."
            Procedure_Return
        End

        Get ComResponseStatusCode Of hoRest To iTemp1
        If (iTemp1 = 200) Begin
            Get ComJsonTypeOf Of hoResult "Responses" To iTemp1
            If (iTemp1 <> 3) Begin
                Showln "Expected Responses object."
                Procedure_Return
            End

            Get ComHasMember Of hoResult "Responses.ExampleItems" To bTemp1
            If (bTemp1 = True) Begin
                Get ComJsonTypeOf Of hoResult "Responses.ExampleItems" To iTemp1
                If (iTemp1 <> 4) Begin
                    Showln "Expected response item array."
                    Procedure_Return
                End

                Move 0 To i
                While (i < (ComSizeOfArray(hoResult, "Responses.ExampleItems")))
                    Set ComI Of hoResult To i
                    Get ComJsonTypeOf Of hoResult "Responses.ExampleItems[i].PK.S" To iTemp1
                    Get ComStringOf Of hoResult "Responses.ExampleItems[i].PK.S" To sTemp1
                    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
                        Showln "Missing or invalid Responses.ExampleItems[i].PK.S."
                        Procedure_Return
                    End

                    Get ComJsonTypeOf Of hoResult "Responses.ExampleItems[i].SK.S" To iTemp1
                    Get ComStringOf Of hoResult "Responses.ExampleItems[i].SK.S" To sTemp1
                    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
                        Showln "Missing or invalid Responses.ExampleItems[i].SK.S."
                        Procedure_Return
                    End

                    Get ComStringOf Of hoResult "Responses.ExampleItems[i].PK.S" To sTemp1
                    If (sTemp1 <> "group-1") Begin
                        Showln "Unexpected partition key."
                        Procedure_Return
                    End

                    Get ComStringOf Of hoResult "Responses.ExampleItems[i].SK.S" To sReturnedId
                    Get ComAddInt Of hoFound sReturnedId 1 To iSuccess
                    Showln "Found SK: " sReturnedId
                    Get ComHasMember Of hoResult "Responses.ExampleItems[i].Data.S" To bTemp1
                    If (bTemp1 = True) Begin
                        Get ComStringOf Of hoResult "Responses.ExampleItems[i].Data.S" To sTemp1
                        Showln "Data: " sTemp1
                    End

                    Move (i + 1) To i
                Loop

            End

            Get ComHasMember Of hoResult "UnprocessedKeys" To bTemp1
            If (bTemp1 = True) Begin
                Get ComJsonTypeOf Of hoResult "UnprocessedKeys" To iTemp1
                If (iTemp1 <> 3) Begin
                    Showln "Expected UnprocessedKeys object."
                    Procedure_Return
                End

                Get pvComObject of hoPending to vPending
                Get ComObjectOf2 Of hoResult "UnprocessedKeys" vPending To iSuccess
                If (iSuccess <> True) Begin
                    Showln "Could not read unprocessed entries."
                    Procedure_Return
                End

                Get ComSize Of hoPending To iTemp1
                If (iTemp1 > 0) Begin
                    //  Retry exactly the unprocessed map; do not resend already completed entries.
                    Send ComClear To hoBody
                    Get pvComObject of hoPending to vPending
                    Get ComAppendObjectCopy Of hoBody "RequestItems" vPending To iSuccess
                    If (iSuccess <> True) Begin
                        Showln "Could not prepare remaining requests."
                        Procedure_Return
                    End

                    Get ComUpdateString Of hoBody "ReturnConsumedCapacity" "TOTAL" To iSuccess
                    Move True To iRetry
                End

            End

        End
        Else Begin
            //  These documented batch throttling failures mean the batch could not be processed.
            //  Do not apply this rule to timeouts, HTTP 500, or arbitrary errors.
            Send ComClear To hoErrorType
            Get ComJsonTypeOf Of hoResult "__type" To iTemp1
            If (iTemp1 = 1) Begin
                Get ComStringOf Of hoResult "__type" To sTemp1
                Get ComAppend Of hoErrorType sTemp1 To iSuccess
            End

            Get ComResponseStatusCode Of hoRest To iTemp1
            Get ComEndsWith Of hoErrorType "ProvisionedThroughputExceededException" True To bTemp1
            Get ComEndsWith Of hoErrorType "ThrottlingException" True To bTemp2
            If ((iTemp1 = 400) And ((bTemp1 = True) Or (bTemp2 = True))) Begin
                Move True To iRetry
            End
            Else Begin
                Get ComResponseStatusCode Of hoRest To iTemp1
                Get ComGetAsString Of hoErrorType To sTemp1
                Showln "Batch failed. HTTP: " iTemp1 "; type: " sTemp1
                Procedure_Return
            End

        End

        If (iRetry = True) Begin
            If (iAttempt = 8) Begin
                Get ComWriteFile Of hoBody "dynamodb-batch-get-pending.json" To iSuccess
                If (iSuccess <> True) Begin
                    Showln "Could not save pending work; retain the current request privately."
                    Procedure_Return
                End

                Showln "Retry limit reached. Incomplete work saved to dynamodb-batch-get-pending.json; later input chunks, if any, were not sent."
                Procedure_Return
            End

            //  Full jitter, exponential growth, capped at five seconds.
            Get ComRandomInt Of hoRandom 0 iDelayCap To iDelayMs
            Send ComSleepMs To hoConnection iDelayMs
            Move (iDelayCap * 2) To iDelayCap
            If (iDelayCap > 5000) Begin
                Move 5000 To iDelayCap
            End

        End

    Loop

    //  Only now can omitted keys be reported as not found: all retries completed.
    Move 0 To i
    While (i < (ComCount(hoRequestedIds)))
        Get ComContains Of hoFound (ComStringAt(hoRequestedIds, i)) To bTemp1
        If (bTemp1 = False) Begin
            Get ComStringAt Of hoRequestedIds i To sTemp1
            Showln "Not found SK: " sTemp1
        End

        Move (i + 1) To i
    Loop

    Showln "Batch read complete."


End_Procedure