How to rate limit automation execution using a rolling time window

Is there a way to implement something similar to an API rate limiting pattern of a sliding window? I had a motion sensor go rogue last night and it fired off the automation it’s tied to way too often. I have cameras watching the area of this automation and it definitely should not have triggered this frequently. This sensor & execution have otherwise been working flawlessly the past few months.

Normal example: Motion detected, conditions met, execute automation. Typically will not execute again for hours and most times, it won’t execute for the remainder of the day.
Abnormal example: Motion detected, conditions met, execute automation. Two minutes later, it executes successfully. Five minutes after that, it executes successfully. One minute after that, it executes successfully. And so on through the night.

I’m trying to implement a throttling pattern that would enable X runs within a rolling window.

Future example: Automation can run three times within a 10 minute period. If it tries to run a fourth time within 10 minutes, the execution is suppressed.

Time boundaries would be in minutes does not need seconds-level precision. Is it possible to do this and be durable enough to survive an HA reboot? Or is there something simple to get this implemented now and make it HA reboot-proof in the future? These sensors have been otherwise rock solid to this point and I have realized as I build more in HA, these types of error conditions should be considered.

You could use a date/time helper.
Put in a condition of it needing to be > 10 minutes after the date/time in that helper.
Add an action to set that date/time helper to the current date/time.

It’s not exactly what you have described, but one way to throttle how often the actions are executed is to use a template condition based on the last_triggered attribute of the automation:

condition: template
value_template: |
  {% set last_run = this.attributes.last_triggered|default(as_datetime(0),1) %}
  {{ now() >=  last_run + timedelta(minutes = 3) }}

If you really want to implement the rolling window, you can do it, but you’d need a trigger-based template sensor to store the last 3 times the automation has triggered. In your automation, you’d check whether the oldest of those is older than 10 minutes ago.

So, it’s possible, but probably not worth the hassle.

1 Like

Um, fix the underlying problem of too many triggers.
Spiders set up camp on your sensor? Bushes need trimming with high winds around? Some thief casing out your joint with a laser pointer to get your motion sensor bypassed?

Change it to single mode so only one can run at a time.
Set the mode to ignore errors so when it tries to run again it doesn’t spam the log.
Add a delay for however long you want to throttle at the end of the automation.

1 Like