JRun
JRun

Reputation: 51

Fire & Forget calls in Azure Functions

I have a long running task in an Azure function which I want to run in a background thread using Task.Run. I don't care about the result.

public static async Task Run(...)
{
 var taskA = await DoTaskA();     
 Task.Run(new Action(MethodB));
 ....
 // return result based on taskA
}

Is this an acceptable pattern in Azure functions? (this is an HTTP trigger function)

I know this could also be done by adding a message to a queue and have another function execute this task but I want to know the pros and cons of starting run long running tasks in a background thread in Azure functions.

Upvotes: 5

Views: 5540

Answers (3)

Marie Hoeger
Marie Hoeger

Reputation: 1331

Depending on how complex your scenario is, you may want to look into Durable Functions. Durable Functions gives you greater control over a variety of scenarios, including long-running tasks.

Upvotes: 4

evilSnobu
evilSnobu

Reputation: 26414

No, no and no.

Have your HTTP triggered function return a 202 Accepted, the results of which you post to a blob URL later on. The 202 should include a Location header that points to the soon to exist blob URL and maybe a Retry-after header as well if you have a rough idea how long the processing takes.

The long processing task should be a queue triggered function. Why? Because things don't always go according to plan and you may need to retry processing. Why not have the retry built in.

Upvotes: 2

Kzryzstof
Kzryzstof

Reputation: 8402

It might be best to have an Azure Function running TaskA and have it post a message in a ServiceBus which would trigger another Azure Function running TaskB when something is posted in that ServiceBus since no answer is needed anyway.

Here is the example shown on microsoft's website:

[FunctionName("FunctionB")]                    
public static void Run(
    [ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")] 
    string myQueueItem, 
    TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    MethodB();
}

In that situation, you do not have to start a new task. Just call MethodB().

That will give you the flexibility the adjust the Plan of your Azure Functions (App Service vs Consumption Plan) and minimize the overall cost.

Upvotes: 6

Related Questions