I have an IotHub trigger which basically saves an incoming id to the database using Entity Framework if such an id does not exist.
[FunctionName("MainFunc")]
public static async Task Run(
[IoTHubTrigger("messages/events",
Connection = "IotHubCompatibleEndpointConnectionString",
ConsumerGroup = "ttx_iothub_trigger_sqldb_cg")]
EventData eventData, ILogger log)
{
string id = GetIdFromMessage(eventData);
var context = new MyEfDbContext();
InsertIfNotExists(id);
DoSomethingElse(context);
context.SaveChanges();
}
The problem is that when there are a lot of messages sent to the iot hub, multiple trigger calls start working in parallel (at least when I debug the trigger) which causes the issue for InsertIfNotExists()
method leading to duplicate key exception when more than 1 record with the same id, not existing in the database, is being processed.
What is the most appropriate way to fix it? Just swallow the exception because the record anyway will appear in the database?