Comment on page
Preventing action loops
Action loops can occur when a Mechanic task triggers an action that, in turn, generates an event that re-triggers the same task. This can lead to unintended consequences like excessive API calls, duplicated data, or even rate-limiting issues. This guide aims to provide you with strategies to prevent such action loops in your Mechanic tasks.
1
{% if event.topic == "shopify/products/update" or event.preview %}
2
{% assign existing_tags = product.tags | split: ", " %}
3
4
{% unless existing_tags contains "NewTag" %}
5
{% action "shopify" %}
6
mutation {
7
tagsAdd(
8
id: {{ product.admin_graphql_api_id | json }},
9
tags: ["NewTag"]
10
) {
11
userErrors {
12
field
13
message
14
}
15
}
16
}
17
{% endaction %}
18
{% else %}
19
{% log "break loop" %}
20
{% endunless %}
21
{% endif %}
Example: Using Timestamps to Prevent Loops
1
{% if event.topic == "shopify/products/update" or event.preview %}
2
{% assign current_timestamp = "now" | date: "%s" %}
3
{% assign time_difference = current_timestamp | minus: product.metafields.custom.last_updated.value %}
4
5
{% if time_difference >= 500 %}
6
{% action "shopify" %}
7
mutation {
8
productUpdate(
9
input: {
10
id: {{ product.admin_graphql_api_id | json }},
11
metafields: [{
12
id: {{ product.metafields.custom.last_updated.metafield.admin_graphql_api_id | json }},
13
namespace: "custom",
14
key: "last_updated",
15
value: {{ current_timestamp | json }},
16
type: "number_integer"
17
}]
18
}
19
) {
20
userErrors {
21
field
22
message
23
}
24
}
25
}
26
{% endaction %}
27
{% comment %}
28
Do your update here
29
{% endcomment %}
30
{% else %}
31
{% log "not so fast" %}
32
{% endif %}
33
{% endif %}
Mechanic has some built-in features to prevent action loops:
- 1.For tasks responding to
mechanic/actions/perform
, Mechanic will detect identical results to their predecessors and mark the task run as failed. - 2.For tasks responding to Shopify update events like
shopify/products/update
, Mechanic will detect repeated, identical task runs and error all action runs generated by the flagged task run.
Preventing action loops is crucial for maintaining the efficiency and reliability of your Mechanic tasks. By implementing conditional checks or using a timestamp-based approach, you can ensure that your tasks operate as intended without causing unintended loops.
Last modified 2mo ago