Error encountered context canceled while in goroutine

I am getting “error encountered context canceled”, I guess it is because the request from the client that initiated the goroutine was returned.
Does it mean that I can’t use the context inside a goroutine?

That message usually means that the client went away, before the request was fully processed and therefore the rest of the processing was cancelled. Using context in such a way is actually strongly recommended to act as a back-pressure mechanism so that the server doesn’t perform unnecessary tasks when clients cancel the request (for whatever reason).

But this actually the behaviour I wanted,
I want to perform some bacground operations after a player login, without holding the player request.
I am creating a goroutine and returning the result to the player. (i don’t really need to wait for the goroutine before returning the result). What other option do I have?
is it ok to simply not use the ctx in this goroutine?

I’d not recommend having background operations after the player leaves.

However if that’s something you have to do you can create a new context using
context.WithTimeout(context.Background(), 5 * time.Second) (of course 5s is an arbitrary value) that ensures the operation finishes within 5 seconds even after the player has left, and avoids having many long-lasting goroutines.

Out of curiosity, what game feature are you building that requires an operation to continue after the player has left?

We are updating player attributes, so they can be used by our segmentation system.
So whenever the player logs in, we need to update the segmentation system with the new values. for example:
days_since_last_purchase.
last_30_days_average_purchase.
I don’t really need to hold the player login GRPC function call until the update is completed. I can return the login result to the player and run the segmentation update in the background.

Do you have any other suggestions for such a scenario?

I’d highly suggest that you use the “Events API” in Nakama to publish an event which contains some custom data that you pass in. This API is non-blocking and returns instantly.

Once an event is published, you can subscribe and consume event somewhere else in your code, and Nakama will manage the event lifecycle incl the event buffer queue. At this stage you can then write your heavy processing logic (or send the event to some third party via HTTP).

3 Likes