Question

I have created a DML trigger (AFTER INSERT, UPDATE, DELETE) on a table
Trigger's logic takes about 30 seconds to execute

So if you change even 1 row, it takes ~ 30 seconds due to trigger execution
Developer asked me "Is there a chance that the trigger could be a fire & forget action?"

I said no, but is it really so ?

Question:

Can trigger be executed in "asynchronous" mode?
Application updates couple of rows in few ms, and thinks that transaction is completed, and then trigger is silently executed under the hood ?

I understand that this actually does not look good from consistency point of view, but still, is it possible ?

Was it helpful?

Solution

As far as I'm aware this is not possible with the triggers feature of Azure / SQL Server. One reason likely being, as you mentioned, it breaks the Consistency property of the ACID principals of a database:

...any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. This prevents database corruption by an illegal transaction...

Triggers are meant to fire transactionally in lockstep with the operation that caused them to fire. Imagine if the row of data that the trigger was dependent on was deleted before the trigger got to execute asynchronously. This could get you into a lot of trouble.

Alternatively, you can have a trigger that simply adds a row to a queue table, and a SQL Agent Job for example, that constantly runs checking that queue table and firing a stored procedure with the logic from your original trigger to emulate an asynchronous event. Perhaps that would improve your workflow?

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top