aws-sdk-go-v2: DynamoDB rate limit error without throttling on the table

Describe the bug

I’m trying to debug a problem where my application is crashing on leaked GoRoutines. While trying to root cause the problem I’ve found some issues that seem to be related with the SDK:

I’m launching 500 GoRoutines to do a PutItem (different PK on each). Only between 200-350 succeed (depending on the run), with the rest returning:

operation error DynamoDB: PutItem, failed to get rate limit token, retry quota exceeded, 0 available, 5 requested

Interestingly, the DDB table is configured as On Demand, and CloudWatch doesn’t show any Throttling errors

Also, when running goleak.VerifyNone(t), the library detects lots of leaked GoRoutine in different states in some part of http libraries. I’ve looked into https://github.com/aws/aws-sdk-go-v2/issues/1434 but the PutItem doesn’t seem to have any response with io.ReadCloser so I’m assuming these aren’t related.

Expected Behavior

  1. I’m assuming rate limit errors should be caused by service throttle errors (DynamoDB) but I can see no evidence in DynamoDB that this is the cause of these errors, so more clarity would be useful (what rate limits am I hitting?)
  2. I would expect that there should be no Goroutine leaks at the end of the operations. This doesn’t seem to be the case.

Current Behavior

  1. Receiving error operation error DynamoDB: PutItem, failed to get rate limit token, retry quota exceeded, 0 available, 5 requested without any throttling evidenced in DynamoDB CloudWatch metrics
  2. Goroutine leaks

Reproduction Steps

Sample below includes commented code to customise the http setting which I used to see how that could change behaviour but couldn’t find any settings that would solve the perceived problem.

package database

import (
	"context"
	"crypto/md5"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"log"

	// "net"
	"runtime"
	"sync"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	// "github.com/aws/aws-sdk-go-v2/aws/transport/http"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/stretchr/testify/assert"
	"go.uber.org/goleak"
)

// func TestMain(m *testing.M) {
// 	goleak.VerifyTestMain(m)
// }

func TestConnectionReuseForPutContentHash(t *testing.T) {
	defer goleak.VerifyNone(t)

	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	svc := databaseConnection(ctx)
	table := "testtable"

	n := runtime.NumGoroutine()

	var wg sync.WaitGroup
	limit := 500
	success := make(chan int, limit)
	s := 0
	go func() {
		for i := range success {
			s = s + i
		}
	}()

	for i := 0; i < limit; i++ {
		wg.Add(1)
		go func(c chan int) {
			defer wg.Done()
			entry := NewHashEntry(
				fakeHash(),
				"175767cb005f8809beb731fd853d0343",
			)
			err := putItem(ctx, svc, table, entry)
			if err == nil {
				c <- 1
			}

		}(success)
	}
	wg.Wait()
	cancel()
	close(success)
	assert.Equal(t, n, runtime.NumGoroutine(), "Number of GoRoutines is different to expected")
	assert.Equal(t, limit, s, "Number of succesful items processed is different to requested")
	// assert.Equal(t, true, false, "forced assert to be sure the test is performing")
}

func fakeHash() string {
	hash := md5.New()
	// used to create a hard enough to repeat hash and avoid PK problems
	s := fmt.Sprintf("%d%s", time.Now().UnixNano(), pseudo_uuid())

	hash.Write([]byte(s))
	hashInBytes := hash.Sum(nil)[:16]
	returnHashString := hex.EncodeToString(hashInBytes)
	return returnHashString
}

// Note - NOT RFC4122 compliant
func pseudo_uuid() (uuid string) {
	b := make([]byte, 16)
	_, err := rand.Read(b)
	if err != nil {
		fmt.Println("Error: ", err)
		return
	}

	uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

	return
}

func databaseConnection(ctx context.Context) *dynamodb.Client {
	// Initialize a session that the SDK will use to load
	// credentials from the shared credentials file ~/.aws/credentials
	// and region from the shared configuration file ~/.aws/config.
	// httpCustomClient := http.
	// 	NewBuildableClient().
	// 	WithTimeout(time.Second * 5).
	// 	WithDialerOptions(func(d *net.Dialer) {
	// 		d.KeepAlive = -1
	// 		d.Timeout = time.Millisecond * 1000
	// 	})
	// cfg, err := config.LoadDefaultConfig(ctx, config.WithHTTPClient(httpCustomClient))
	cfg, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Printf("unable to load SDK config, %v", err)
	}

	return dynamodb.NewFromConfig(cfg)
}

// Generic function to record a generic object into DDB
func putItem(ctx context.Context, svc *dynamodb.Client, table string, item interface{}) error {

	av, err := attributevalue.MarshalMap(item)
	if err != nil {
		log.Printf("Got error marshalling new item: %s", err)
		return err
	}

	tableName := table

	input := &dynamodb.PutItemInput{
		Item:      av,
		TableName: aws.String(tableName),
	}

	_, err = svc.PutItem(ctx, input)
	if err != nil {
		log.Printf("Got error calling PutItem: %s", err)
	}

	return err

}

func NewHashEntry(hashvalue string, filenamehash string) *HashEntry {
	return &HashEntry{
		Pk: hashvalue,
		Sk: filenamehash,
	}
}

type HashEntry struct {
	Pk string `dynamodbav:"pk"`
	Sk string `dynamodbav:"sk"`
}

Possible Solution

No response

Additional Information/Context

Error is reproducible in both Linux and MacOS

AWS Go SDK version used

Go 1.18 (and Go 1.16)

Compiler and Version used

go version go1.18 darwin/amd64

Operating System and version

MacOs 12.2.1 and Amazon Linux 2

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 16
  • Comments: 16 (3 by maintainers)

Most upvoted comments

I was experiencing a similar issue with Kinesis client. Based on my investigation, this error is triggered by throttling implemented in retry module.

In my case, I was using the same client instance across a very large number of Go routines. As a result when retries are attempted, all Go routines use the same token bucket and run out of tokens. Good news is, token bucket size is configurable. I was able to fix this by adjusting the number of tokens when constructing the config as shown below.

cfg, err := config.LoadDefaultConfig(ctx, config.WithRetryer(func() aws.Retryer {
	return retry.NewStandard(func(so *retry.StandardOptions) {
		so.RateLimiter = ratelimit.NewTokenRateLimit(1000000)
	})
}))

failed to get rate limit token, retry quota exceeded, 0 available, 5 requested

This behavior is expected, but I’d say we’ve clearly done a poor job of communicating how this works in our public documentation.

This error surfaces from a client-side rate-limiting mechanism introduced in SDK v2 (it’s part of our newer cross-SDK specification for retry behavior that was meant to standardize how this works across SDKs). @buddhike’s comment above is accurate at a high level.

Fortunately, this is configurable and @buddhike’s solution is going to be functionally adequate for most in the absence of an explicit “off” switch. @yuseferi mentioned performance concerns, but there shouldn’t be any - each operation still has the configured maximum number of attempts that it will obey.

I’m going to address two things here as followup:

  • document this in our retries and timeouts dev guide entry
  • add an explicit “no-op” rate limiting implementation that you can pull in when configuring a retryer

I’m seeing this same issue. This is fully reproducible in a unit test I have against a local DynamoDB.

DynamoDB: Query, failed to get rate limit token, retry quota exceeded, 3 available, 5 requested
  1. The error does not occur on Linux – macOS only
  2. If I turn on the Golang race detector the error does not occur (which points to a tricky bug in the SDK or one of it’s dependencies)

Ok, additional tests show that forcing the SDK client to use the HTTP endpoint avoids the crashes I kept seeing. This allows me to enable KeepAlives again and regain performance, but with the obvious risk of not having encrypted traffic between my client and the server. The combination of keep-alives and tls enabled produce panics when trying to call DynamoDB with many items (500 concurrent and 10000 items total) - not sure where the problem lies, yet