Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flush if next record would make the request size too big #9

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions kinesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
k "github.com/aws/aws-sdk-go/service/kinesis"
)

// Size limits as defined by http://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html.
const (
maxRecordSize = 1 << 20 // 1MiB
maxRequestSize = 5 << 20 // 5MiB
megaByte = 1 << 20
maxRecordSize = megaByte
maxRequestSize = 5 * megaByte
)

// Errors.
Expand All @@ -39,7 +39,7 @@ func New(config Config) *Producer {

// Put record `data` using `partitionKey`. This method is thread-safe.
func (p *Producer) Put(data []byte, partitionKey string) error {
if len(data) > maxRecordSize {
if len(data)+len(partitionKey) > maxRecordSize {
return ErrRecordSizeExceeded
}

Expand Down Expand Up @@ -73,6 +73,7 @@ func (p *Producer) Stop() {
// loop and flush at the configured interval, or when the buffer is exceeded.
func (p *Producer) loop() {
buf := make([]*k.PutRecordsRequestEntry, 0, p.BufferSize)
bufSize := 0
tick := time.NewTicker(p.FlushInterval)
drain := false

Expand All @@ -82,11 +83,21 @@ func (p *Producer) loop() {
for {
select {
case record := <-p.records:
recordSize := len(*record.PartitionKey) + len(record.Data)

if bufSize+recordSize > maxRequestSize {
p.flush(buf, "request size")
buf = nil
bufSize = 0
}

buf = append(buf, record)
bufSize += recordSize

if len(buf) >= p.BufferSize {
p.flush(buf, "buffer size")
buf = nil
bufSize = 0
}

if drain && len(p.records) == 0 {
Expand All @@ -97,6 +108,7 @@ func (p *Producer) loop() {
if len(buf) > 0 {
p.flush(buf, "interval")
buf = nil
bufSize = 0
}
case <-p.done:
drain = true
Expand Down