Is setting task state expensive?

I have a background task which sets fields of its task_state at various points in its process.

Having just discovered that task_state has the “update” method I’ve realised that I could redesign the task to make just one call to update its state rather than set ~6 fields in different lines of code, i.e. I could replace:

anvil.server.task_state[“field_1”] = “A”
anvil.server.task_state[“field_2”] = “B”
anvil.server.task_state[“field_3”] = “C”
etc

with anvil.server.task_state.update(field_1=“A”, field_2=“B”, field_3=“C” etc)

My question is: is there any value (other than perhaps code clarity) to making this change? Is setting task_state writing to a data table somewhere and hence somewhat expensive? Or would this be a pointless change?

(My app has high usage and has issues with large numbers of calls to data tables)

Thanks!

I suspect that update actually operates more like a database transaction, than three separate lines would.

Imagine that “C” isn’t a literal, but a function call. If that call raises an exception, then update would not get called, and none of the fields would be updated. If that happened in the prior, three-line code, then the first two updates would have already occurred.

So, to me, the value would be in the all-or-nothing effect. The (implicit) documentation of that intent would be a close second.

The short answer to this is no! Setting your current BG task state is very cheap, so you can update it as often as you like. (It’s when you call get_state() on a task that we do the expensive operation of going and reaching into the running process to get a copy of its current state.)

3 Likes

Very helpful, thanks!