azure-sdk-for-go: Memory leak when eventhub partitionClient.ReceiveEvents times out often

Bug Report

My application seems to spike in memory after many timeout cancellations of ReceiveEvents from partitionClients. We’ve deployed our app in several data centers and the trend seems to be that the least active data centers often ends up in a memory spike (see pprof images below). Our event reception needs to be relatively instantaneous so we’ve set our timeout to 5 seconds. Could the frequent timeout cancellations cause an issue preventing disposals somewhere? Judging by the stack trace, it seems to be related to the ‘retry’ logic.

Additional details: Our app is deployed in AU and EU and both instances listen to an event hub in eastus. Could a network related issue contribute to the problem?

We’ve also made sure we have the fixed version mentioned here: https://github.com/Azure/azure-sdk-for-go/issues/24195

I also enabled the SDK logs for a period and found some suspicious logs:

{"time":"2025-06-02T19:36:58.71573561Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Consumer","Message":"No events received, returning error context deadline exceeded"}
{"time":"2025-06-02T19:36:58.746724685Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Auth","Message":"(<eventhub>/ConsumerGroups/<consumer-group>/Partitions/6) next refresh in 2m0s"}
{"time":"2025-06-02T19:36:58.746861698Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Auth","Message":"(<eventhub>/ConsumerGroups/<consumer-group>/Partitions/23) negotiate claim, failed: context canceled"}
{"time":"2025-06-02T19:36:58.746936457Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Auth","Message":"(NegotiateClaimRefresh) Retry attempt 0 was cancelled, stopping: context canceled"}
{"time":"2025-06-02T19:36:58.74695405Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Auth","Message":"[<eventhub>/ConsumerGroups/<consumer-group>/Partitions/23] fatal error, stopping token refresh loop: context canceled"}
{"time":"2025-06-02T19:36:58.746983555Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Conn","Message":"(c:1,l:4BITV,p:23) Error when cleaning up old link for link recovery: context deadline exceeded"}
{"time":"2025-06-02T19:36:58.74702945Z","level":"INFO","msg":"EventHub Log.","event":"azeh.Consumer","Message":"(c:1,l:4BITV,p:23) Retry attempt 0 was cancelled, stopping: context deadline exceeded"}

(Additional pprof screenshots in ‘details’) Image

Imported package: github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs SDK version: v1.3.2 Go version: go1.24.3

Example code:

package main

import (
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs"
)

const (
	eventWait      = 5 * time.Second
	eventWaitCount = 100
)

func readEventHub(ctx context.Context, connectionString string, consumerGroup string, checkpointStore azeventhubs.CheckpointStore) error {
	consumerClient, err := azeventhubs.NewConsumerClientFromConnectionString(connectionString, "", consumerGroup, nil)
	if err != nil {
		return err
	}

	processor, err := azeventhubs.NewProcessor(consumerClient, checkpointStore, nil)
	if err != nil {
		return err
	}

	//  for each partition in the event hub, create a partition client with processEvents as the function to process events
	dispatchPartitionClients := func() {
		for {
			partitionClient := processor.NextPartitionClient(ctx)

			if partitionClient == nil {
				break
			}

			go func() {
				if err := processEvents(ctx, partitionClient); err != nil {
					if errors.Is(err, context.Canceled) {
						log.Printf("event processing error: %v", err)

						return
					}
				}
			}()
		}
	}

	// run all partition clients
	go dispatchPartitionClients()

	go func() {
		if err := processor.Run(ctx); err != nil {
			if errors.Is(err, context.Canceled) {
				// ignore context cancelled error
				return
			}

			log.Printf("processor run error: %v", err)
		}
	}()

	return nil
}

func processEvents(ctx context.Context, partitionClient *azeventhubs.ProcessorPartitionClient) error {
	defer func() {
		if err := partitionClient.Close(ctx); err != nil {
			log.Printf("close error: %v", err)
		}
	}()

	for {
		timedCtx, cancel := context.WithTimeout(ctx, eventWait)
		events, err := partitionClient.ReceiveEvents(timedCtx, eventWaitCount, nil)
		cancel()

		if err != nil && !errors.Is(err, context.DeadlineExceeded) {
			return err
		}

		for _, event := range events {
			// Placeholder for event processing logic
			var payload json.RawMessage
			_ = json.Unmarshal(event.Body, &payload)
		}

		if len(events) > 0 {
			if err := partitionClient.UpdateCheckpoint(ctx, events[len(events)-1], nil); err != nil {
				return err
			}
		}
	}
}

Image

Image

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Comments: 16 (5 by maintainers)

Most upvoted comments

Right.

I doubled checked our pprof file and the screenshots I’ve attached are indeed from the inuse_space option of the pprof UI. The alloc_space looks vastly different.

I’ll try and get a second memory profile to be absolutely sure, but I would take my original screenshots as “inuse”

Here are some graphs of the memory usage over time. The receive timeout here is set to 5sec, the pod was restarted after reaching its memory limit: Image We then tried to configure the receive timeout to 1minute, here is an overview of the memory: Image

For our CA and US2 deployments, the memory remains constant around 200Mi, ex: Image

@richardpark-msft , thanks for the feedback.

Here are the answers to your follow up questions. Please let me know if it’s unclear or if additional information is needed.

How many partitions do you have? Each eventhub is configured to 32 partitions. Each instance is listening to 4 eventhubs simultaneously. 2 separate regions and each with its own backup for redundancy.

How many partitions are typically owned by each Processor? We have two instances of our service running in separate Kubernetes pods, so each processor probably has around 16 partitions.

How many Processor instances are you running? So that’s 1 processor per event hub. So each instance has 4 processors each with up to 16 partitions. So up to (4*16) 64 partitions in a single instance across 4 processors.

In the logs (for any instance) do you see any OwnershipLost errors, or similar? I’m curious if what we’re seeing here is a “rebalancing” happening, where one of your partition processors is suddenly shifting to own more partitions than it normally does.

Yes, we noticed instances of the ownershiplost error where the receiver has identical guids and other instances where the guids are different:

// Guids are the same
(ownershiplost): *Error{Condition: amqp:link:stolen, Description: New receiver '58e8bb7b-0d0a-4463-4387-c228ba85f313' with higher epoch of '0' is created hence current receiver '58e8bb7b-0d0a-4463-4387-c228ba85f313' with epoch '0' is getting disconnected. If you are recreating the receiver, make sure a higher epoch is used. TrackingId:020b706a000267dc000069b5683e0938_G8_B20, SystemTracker:<eventhub>, Timestamp:2025-06-02T20:27:46, Info: map[]}

// Guids are different
(ownershiplost): *Error{Condition: amqp:link:stolen, Description: New receiver '49e8934b-eb2c-4e16-445d-d0dc28b01117' with higher epoch of '0' is created hence current receiver '2edee78f-669c-487e-7568-e33604add7f0' with epoch '0' is getting disconnected. If you are recreating the receiver, make sure a higher epoch is used. TrackingId:8bfe0c1e000267de001a9c80683f5d89_G5_B17, SystemTracker:<eventhub>, Timestamp:2025-06-03T21:13:35, Info: map[]} 

When you see the memory spike how memory are we talking about? Does it cause your app to die, slow down or exhibit any other odd behavior? We have 2 kubernetes pods running our service in each environment. Each pod is configured to 500mb max. The pods crash with a OOMKilled error.

I hope this is helpful. We are a bit stumped as to why this is only happening in our AU and WESTEU data centers while the CanadaCentral and EastUS2 data centers are perfectly stable. Each deployment listens to a regional eventhub AND a singular eventhub is eastus. The vast majority of eventhub activity is coming from that common eastus eventhub which is consumed via separate consumer groups by each deployment.

@lcerone, thanks for the detailed bug report, I’ll take a look.