Cannot publish to SNS from a thread in AWS Lambda function
My lambda function written in .net core is able to publish a message to an SNS topic successfully. However, if I publish the message by creating a new thread (using Task.Run(() =>) in the Lambda function, then the thread just hangs when executing the IAmazonSimpleNotificationService.PublishAsync() method. The thread also hangs if I call IAmazonSimpleNotificationService.ListTopicsAsync(new ListTopicsRequest()).
So does any new thread launched in AWS Lambda require a specific context?
Hi @omairs80, are you debugging this through the Lambda Test Tool or do you have some logging that would make you believe the publish on the new thread is hanging? I wasn't able to reproduce your problem. Both the publish from the main thread and the Task.Run publish worked for me multiple times.
What versions of our code are you using?
Thanks @klaytaybai I have deployed my lambda in AWS. I am just using Console.WriteLine() for the cloudwatch logging. Code is built in .NET Core 2.1
Please note that I have configured a VPC on my lambda i.e. 2 subnets and 1 security group. I have already created an SNS endpoint as well. Publishing to SNS topics works fine from the main execution thread but not from a new thread that I start using Task.Run().
Here is my class:
public class SnsEventPublisher
{
private readonly IAmazonSimpleNotificationService _snsService;
public SnsEventPublisher(IAmazonSimpleNotificationService snsService)
{
_snsService = snsService;
}
// Publishes to Sns in a worker thread
public void PublishInNewThread(string message, string topicArn)
{
Task.Run(() =>
{
var request = new PublishRequest { Message = message, TopicArn = topicArn };
try
{
Console.WriteLine("Going to publish message in new thread");
var response = _snsService.PublishAsync(request).Result;
Console.WriteLine("Message published: " + response.MessageId);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
});
}
// Publishes to Sns in the same thread
public void Publish(string message, string topicArn)
{
var request = new PublishRequest { Message = message, TopicArn = topicArn };
try
{
Console.WriteLine("Going to publish message");
var response = _snsService.PublishAsync(request).Result;
Console.WriteLine("Message published: " + response.MessageId);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
The IAmazonSimpleNotificationService is injected by .NET Core's dependency injection (DI). So Publish() works fine but PublishInNewThread() does not.
In the Cloudwatch logs, I see that for PublishInNewThread(), the last log entry is of "Going to publish message in new thread".
The PublishInNewThread method is attempting publish a message in a Task but nothing is waiting for that task to complete. So I assume your Lambda handler function calls this method which kicks off the task and the returns right away. Since the Lambda function handler method returns that signals back to Lambda that the incoming event has been processed and then freezes the Lambda compute environment.
You need to have PublishInNewThread method return back the Task and then having the caller method await on the return task. Below is a rewrite of your method that uses async/await and the task is returned. The calling method should then call PublishInNewThread and await the method call. You should change the method signature of your lambda function handler to return back the Task as well.
public class SnsEventPublisher
{
private readonly IAmazonSimpleNotificationService _snsService;
public SnsEventPublisher(IAmazonSimpleNotificationService snsService)
{
_snsService = snsService;
}
public async Task PublishInNewThread(string message, string topicArn)
{
var request = new PublishRequest { Message = message, TopicArn = topicArn };
try
{
Console.WriteLine("Going to publish message in new thread");
var response = await _snsService.PublishAsync(request);
Console.WriteLine("Message published: " + response.MessageId);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Thanks for your reply @normj. So once the Lambda event handler method returns, then any worker threads that haven't ended will just freeze/stop working? I searched the AWS documentation, but nothing mentions the Lambda compute environment would freeze.
Some interesting things to note:
- If my lambda handler method calls
Publishand thenPublishInNewThread, both the publishes work. - If my lambda handler method only calls
PublishNewThread, it does not work and hangs
I found out about this needing to be sure you await the other day when I was trying to report errors with rollbar.net, because the methods were async and I wasn't awaiting them my lambda would throw an exception, start the error reporting and then stop executing because it had finished.
AFAIK doing a
Task.Delay(TimeSpan.FromSeconds(30));
In a lambda handler (and pretty much nothing else) but not awaiting it, you will your entire lambda run real quick. It certainly won't report it ran for 30 seconds.
@beeradmoore Sorry I'm confused what you are saying. Were you expecting Task.Delay to block without awaiting the return Task object from Task.Delay?
@omairs80 I'm surprised that calling Publish and then PublishInNewThread causes both messages to be published. I can see it working the other way so that the message from PublishInNewThread was published in the background thread while the synchronous Publish was blocked. But leaving non awaiting Task will cause undefined behavior depending on the task scheduler and the rate events are sent in.
@normj not expecting it to block. My personal experience was with Rollbar.net when I would do a (pseudocode) Roller.Instance.SendError(myException);. It wasn't an awaitable method, but there as a 2nd parameter for options which had a bool to make the underlying HttpClient run synchronous. It's probably poor library design on their behalf and they should expose some sort of SendErrorAsync method.
I was pointing out that I was running into a similar problem which you described is the problem here
is attempting publish a message in a Task but nothing is waiting for that task to complete. Because lambda will quit once its done, it doesn't care if something synchronous is trying to complete.
I was pointing out to @omairs80 that if you don't await something correctly (eg Task.Delay for super simple example, HttpClient request would probably have been a better example), that when lambda reaches the end of its calling method it doesn't care if there is things still happening on a background thread in an un-awaited task that it will just exit.