The concurrency feature in GitHub Actions can be quite powerful, even though many of you are unaware of it. This feature can help solve these two problems in a clean way:
The concurrency feature in Actions helps you address exactly these problems. The big picture idea is pretty simple: You add a “key” to a workflow or job such that
The following snippet can be specified at a workflow or the job level.
concurrency: group: ${{ github.workflow }}
cancel-in-progress: true
Breaking this snippet down:
Consider this example: suppose you use the above concurrency state for a workflow that runs your unit tests. Let’s say Alice pushes a commit to a branch “Alice test” and the unit test jobs begin. While they’re running, suppose Bob pushes a commit to a branch “Bob test”. Since unit test jobs from both Alices and Bob's branches, have the same “key,” Alice’s job would be canceled midway, and only Bob’s job would run to completion.
The recommended solution is to make the “key” include the PR name so it only runs the latest commit within the context of a given PR, and does not hamper runs on other PRs in the repository. github.head_ref is the source branch of the pull request in a workflow run.
concurrency: group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
Here’s the official Github page on using concurrency. In our experience, smart use of concurrency is one of the most effective ways of reducing your GitHub Actions bill. Companies can often cut 10% of their spending by effectively leveraging the concurrency feature.