Cloud Computing

How to Fix GitHub Actions Workflow Timeouts and Optimize Build Speeds

GitHub Actions makes it easy to automate testing, building, and deploying applications. However, slow workflows and unexpected timeouts can delay deployments…

D
DevByteTechnical Author
Published
19 min read5 views
How to Fix GitHub Actions Workflow Timeouts and Optimize Build Speeds

If you've worked on a project with GitHub Actions, you've probably experienced this situation: you push a small code change, open a pull request, and wait for your CI pipeline to finish. A few minutes later, the workflow is still running. Eventually, it fails with a timeout error.

Sometimes the problem is obvious. A test takes too long, a dependency installation gets stuck, or a deployment command never finishes.

But other times, the workflow simply becomes slower as the project grows. A build that originally took two minutes starts taking eight minutes, and every pull request becomes a little more frustrating.

I've found that the first thing to understand is that a workflow timeout and a slow build are not necessarily the same problem. Increasing the timeout may prevent a job from failing, but it doesn't make the build faster. Similarly, adding a cache won't fix a test process that's waiting forever for a database connection.

The right approach is to identify where the time is being spent, fix the underlying issue, and then optimize the workflow.

In this guide, we'll look at how GitHub Actions timeouts work, how to debug slow workflows, how to cache Node.js dependencies, how to run jobs in parallel, and how to build a practical CI pipeline for a Node.js application.

1. Understanding GitHub Actions Workflow Timeouts

GitHub Actions workflows consist of jobs, and each job can contain multiple steps.

For example, a typical Node.js CI pipeline might look like this:

Developer pushes code
        |
        v
GitHub Actions workflow starts
        |
        v
Checkout repository
        |
        v
Install dependencies
        |
        v
Run linting
        |
        v
Run tests
        |
        v
Build application
        |
        v
Workflow succeeds

Each step takes time, and the total execution time depends on your codebase, dependencies, runner resources, and workflow configuration.

If a job exceeds its configured timeout, GitHub Actions cancels the job.

You can configure the timeout using timeout-minutes at the job level:

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Run build
        run: npm run build

In this example, the job has a 15-minute timeout.

If the job doesn't finish within that period, GitHub Actions cancels it.

The important detail is that the timeout applies to the job's execution, not just the build command.

That means checkout, dependency installation, testing, and other steps contribute to the total job duration.

Job timeout vs. step timeout

GitHub Actions also supports timeout-minutes for individual steps.

For example:

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - name: Run unit tests
        run: npm test
        timeout-minutes: 5

Here, the entire job has a 20-minute limit, but the test step has a five-minute limit.

This is useful when you know that a particular operation should finish within a reasonable amount of time.

If tests normally finish in 60 seconds but occasionally hang for several minutes, a step timeout can prevent that problem from consuming the entire job's execution window.

One thing to remember: increasing the job timeout does not automatically increase every step's explicitly configured timeout.

Choose timeout values based on what each operation should reasonably take, rather than assigning an arbitrarily large number to every job.

You can learn more in the official GitHub Actions workflow syntax documentation.

2. Why Do GitHub Actions Workflows Time Out?

Before changing your YAML configuration, identify what is actually causing the delay.

There are several common reasons.

1. Dependency installation takes too long

For a Node.js project, this step can be expensive:

- name: Install dependencies
  run: npm install

If your application has a large dependency tree, npm may spend considerable time downloading packages and resolving dependencies.

This becomes especially noticeable when every workflow run starts on a fresh runner.

Without caching, GitHub Actions may need to download many of the same packages repeatedly.

2. Tests are running sequentially

Suppose your project has three independent test suites:

Unit tests:       3 minutes
Integration tests: 4 minutes
E2E tests:        5 minutes

If you run them sequentially, the total test execution time is approximately 12 minutes, excluding setup overhead.

Some test suites can run in parallel, reducing the overall duration.

However, parallel execution only helps when the tasks are sufficiently independent and the runner has enough resources.

3. Build scripts contain unnecessary work

A build script might compile TypeScript, generate documentation, run tests, bundle the application, and execute a separate validation process.

Not every operation needs to run in every workflow.

For example, generating a production bundle on every test-only job may waste time if a separate build job already validates the bundle.

The goal is to run the checks required for each event without repeating expensive operations unnecessarily.

4. A command is waiting indefinitely

Sometimes the workflow isn't slow at all. A process is simply waiting for something that never happens.

Examples include:

  • A test waiting for a database connection.

  • A server starting without a readiness check.

  • A deployment command waiting for interactive input.

  • A script waiting for a child process to exit.

  • A network request that never completes.

  • A test suite with an unresolved asynchronous operation.

In these cases, caching and parallelization won't solve the underlying issue.

5. The runner is running out of resources

Builds involving large JavaScript bundles, TypeScript compilation, or multiple concurrent test processes can consume substantial CPU and memory.

When a runner is under pressure, operations may become slower even though the code hasn't changed significantly.

If resource constraints are the cause, you may need to reduce concurrency, optimize the build, or select a more suitable runner.

3. Step One: Identify the Slowest Workflow Step

The first optimization should be measurement, not guesswork.

Open your GitHub repository and navigate to the Actions tab.

Select the workflow run that timed out or took longer than expected.

Open the job and inspect its individual steps.

For example, your workflow might show:

Step

Duration

Checkout repository

5 seconds

Set up Node.js

8 seconds

Install dependencies

2 minutes 40 seconds

Run linting

15 seconds

Run tests

3 minutes 20 seconds

Build application

1 minute 50 seconds

In this example, dependency installation and testing consume most of the execution time.

That immediately gives you two areas to investigate.

Caching dependencies may improve installation time, while test optimization may reduce the duration of the test suite.

There is little reason to spend hours optimizing checkout if it takes only five seconds.

Add timestamps to your logs

If your workflow contains a custom script, you can measure the duration of individual commands.

For example:

- name: Install dependencies
  run: |
    echo "Starting dependency installation"
    date -u
    npm ci
    echo "Finished dependency installation"
    date -u

This provides a basic timing reference in the logs.

For more detailed measurements, you can use shell timing:

- name: Build application
  run: |
    time npm run build

On a Linux runner, the time command reports how long the command took to execute.

For a complex workflow, consider collecting durations for dependency installation, tests, compilation, and deployment separately.

Once you know where the time is going, the next steps become much easier.

4. Step Two: Use npm ci Instead of npm install in CI

For npm-based projects, npm ci is generally the preferred choice for automated builds when a valid lockfile is committed.

Compare the two commands:

npm install

and:

npm ci

npm install is designed for general dependency installation and can update the lockfile when dependency specifications require changes.

npm ci installs dependencies according to the existing lockfile and fails if the lockfile and package.json are inconsistent.

It also removes an existing node_modules directory before installing dependencies.

This makes it particularly suitable for clean CI environments.

Update your workflow:

- name: Install dependencies
  run: npm ci

Make sure your repository includes the appropriate lockfile, such as package-lock.json.

Why does this help?

The main benefits are reproducibility and predictable dependency installation.

It doesn't guarantee that npm ci will always be faster than npm install, because installation time depends on the project and dependency tree.

However, it avoids unnecessary dependency resolution changes and gives CI a more consistent installation process.

For more information, see the official npm ci documentation.

5. Step Three: Cache Dependencies in GitHub Actions

Caching is one of the most useful optimizations for workflows that repeatedly install the same dependencies.

GitHub Actions provides caching functionality through actions/cache, and the official actions/setup-node action supports dependency caching for Node.js projects.

For most npm projects, the simplest approach is to configure caching through setup-node.

Here's an example:

name: Node.js CI

on:
  push:
    branches: [main]

  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Build application
        run: npm run build

This is a basic CI workflow for a Node.js application.

The cache: npm option enables caching of npm's package download cache.

It does not directly cache the entire node_modules directory.

On subsequent workflow runs, npm may be able to reuse previously downloaded packages rather than fetching everything again.

The cache is restored based on the dependency lockfile and the caching behavior of the action.

What if your lockfile is in a subdirectory?

If your project has a structure like this:

repository/
├── frontend/
│   ├── package.json
│   └── package-lock.json
└── backend/
    ├── package.json
    └── package-lock.json

You can configure setup-node with the appropriate dependency file path.

For example:

- name: Set up Node.js
  uses: actions/setup-node@v4
  with:
    node-version: 22
    cache: npm
    cache-dependency-path: frontend/package-lock.json

Then run npm commands from the frontend directory:

- name: Install frontend dependencies
  working-directory: frontend
  run: npm ci

If you have independent frontend and backend packages, consider caching each package's dependencies using its own lockfile.

For monorepos, choose a caching strategy that matches your workspace structure rather than assuming one lockfile covers every package.

Can caching make every workflow faster?

Not necessarily.

The first run usually needs to populate the cache. Restoring and saving caches also takes time.

A small project with very few dependencies may see only a modest improvement.

The biggest benefit generally appears in workflows that repeatedly install a large dependency tree.

You should compare actual workflow durations before and after enabling caching.

6. Step Four: Run Independent Jobs in Parallel

Another effective optimization is to separate independent operations into different jobs.

By default, jobs in a workflow can run in parallel unless dependencies are defined through needs or other execution constraints.

Suppose you have three independent checks:

  • Linting.

  • Unit tests.

  • Production build.

You can define separate jobs:

name: Node.js CI

on:
  pull_request:
    branches: [main]

jobs:
  lint:
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - run: npm ci
      - run: npm run lint

  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - run: npm ci
      - run: npm test

  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - run: npm ci
      - run: npm run build

The jobs can run concurrently when GitHub has sufficient runner capacity.

If linting takes one minute, testing takes four minutes, and building takes three minutes, the overall duration may approach the longest individual job rather than the sum of all three.

However, this example also installs dependencies independently in each job.

That means caching can help, but each job still needs to perform its own installation.

You should balance parallel execution against the additional runner time and installation overhead.

When should you use needs?

Not every operation can run independently.

For example, a deployment should normally wait until the required tests and build have succeeded.

You can express that dependency using needs:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Run tests here"

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - run: echo "Deploy application here"

The deployment job starts only after the required test job succeeds.

This keeps the workflow organized without forcing unrelated checks to run sequentially.

7. Step Five: Avoid Installing Dependencies Multiple Times

A common source of wasted time is repeating the same expensive setup operation unnecessarily.

Consider this workflow:

steps:
  - uses: actions/checkout@v4

  - uses: actions/setup-node@v4
    with:
      node-version: 22

  - run: npm ci

  - run: npm run lint

  - run: npm ci

  - run: npm test

  - run: npm ci

  - run: npm run build

The workflow installs dependencies three times.

Unless there's a specific reason to reinstall them, this is unnecessary.

For a single job, a more sensible structure is:

steps:
  - uses: actions/checkout@v4

  - uses: actions/setup-node@v4
    with:
      node-version: 22
      cache: npm

  - run: npm ci

  - run: npm run lint
  - run: npm test
  - run: npm run build

Dependencies are installed once and reused by the subsequent commands.

If you split the operations into separate jobs, each job typically has its own runner environment, so it may need its own dependency installation.

That's one reason why parallel jobs can reduce elapsed time but increase total compute usage.

For a larger project, benchmark both approaches rather than assuming that more jobs always mean better performance.

8. Step Six: Fix Commands That Hang Indefinitely

Sometimes, the real problem isn't the build itself. A command never finishes.

Let's look at a few examples.

Example 1: A server starts and never exits

Suppose your test script looks like this:

{
  "scripts": {
    "test": "node server.js"
  }
}

If server.js starts an HTTP server and keeps listening for requests, the process won't exit automatically.

GitHub Actions will continue waiting until the job or step times out.

If your intention is to run tests, create a test script that starts the server when necessary, executes the tests, and shuts down the server afterward.

Example 2: An integration test waits for a database

Suppose your tests connect to MongoDB but the database isn't available in CI.

The test might keep retrying the connection until the workflow reaches its timeout.

Instead of allowing the process to wait indefinitely, configure a reasonable connection timeout and report a clear error.

For example, a MongoDB connection can use a server-selection timeout:

import mongoose from "mongoose";

await mongoose.connect(process.env.MONGODB_URI, {
  serverSelectionTimeoutMS: 5000
});

This example limits the time spent selecting an appropriate MongoDB server before the connection attempt fails.

The appropriate timeout depends on your environment, and the test process should still handle connection errors correctly.

Example 3: A shell command waits for user input

Interactive commands can be problematic in CI because no developer is present to answer prompts.

For example, a deployment script may ask for confirmation before continuing.

Use the command's supported non-interactive mode where appropriate, and configure required inputs through secure workflow settings.

Don't blindly add flags that bypass all safety checks. Make sure the workflow is explicitly authorized to perform the requested operation.

Example 4: An asynchronous process never completes

Consider this Node.js function:

async function runTask() {
  await new Promise(() => {});
}

The promise never settles.

If the workflow awaits this function, the operation never completes.

In a real application, the same kind of problem can occur when an event listener never fires, a promise is never resolved, or a background task is waiting for an event that doesn't occur.

Use proper error handling, finite timeouts for external operations, and cleanup logic for open resources.

Timeouts are useful safeguards, but they shouldn't replace fixing the underlying problem.

9. Step Seven: Optimize Build Commands and Test Execution

Dependency caching and parallel jobs are helpful, but the application build itself can also become a bottleneck.

For a React or Next.js application, inspect the build scripts and determine which operations consume the most time.

For example:

{
  "scripts": {
    "lint": "eslint .",
    "test": "vitest run",
    "build": "next build"
  }
}

These commands serve different purposes.

Linting checks code quality, tests validate behavior, and the production build verifies that the application can be compiled for deployment.

Avoid running expensive operations more than necessary, but don't remove important checks simply to make the pipeline look faster.

Run only the relevant tests when appropriate

In a large monorepo, a small change to one package may not require every test suite to run.

You can use workspace-specific scripts or change-aware tooling to run relevant checks.

However, the workflow should still include appropriate full validation before a production release.

A good strategy is to run fast, targeted checks on every pull request and comprehensive checks at suitable integration or release stages.

Avoid excessive concurrency

Running more tests simultaneously can reduce elapsed time, but it can also increase memory and CPU usage.

If your test suite launches too many workers, the runner may spend more time managing resources than executing useful work.

For example, if a test runner supports a worker limit, start with a reasonable value and compare results.

The correct limit depends on the runner's resources and the characteristics of your tests.

Reduce unnecessary build work

Consider whether your build process can reuse generated artifacts, avoid redundant compilation, or skip expensive work that isn't relevant to a particular job.

For larger JavaScript projects, incremental builds and monorepo build systems may help.

The important thing is to measure the change and verify that the optimized build still produces the correct output.

10. Step Eight: Use Concurrency to Cancel Obsolete Workflow Runs

Another useful optimization is preventing outdated workflow runs from consuming resources after newer commits arrive.

Imagine pushing five commits to the same pull request.

If every workflow continues running, GitHub Actions may spend time testing changes that are already superseded by newer code.

You can configure concurrency:

name: Node.js CI

on:
  push:
    branches: [main]

  pull_request:

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - run: echo "Run CI checks here"

The concurrency group identifies runs that belong to the same workflow and pull request or branch.

With cancel-in-progress: true, a newer run in the same group can cancel an older in-progress run.

This is useful for CI workflows where only the latest commit needs validation.

However, be careful when applying this pattern to deployments or workflows with important side effects.

You generally don't want a newer event to interrupt a production operation halfway through without considering the consequences.

For deployment workflows, choose concurrency rules based on whether cancellation is safe and whether deployments must occur in order.

11. Step Nine: Configure Separate Timeouts for Different Tasks

A good workflow doesn't need the same timeout for every operation.

For example:

  • Linting might normally take less than two minutes.

  • Unit tests might take five minutes.

  • Integration tests might need ten minutes.

  • A production build might take several minutes.

  • Deployment may require a different limit based on the infrastructure involved.

These are examples, not universal recommendations. Measure your own project and set realistic limits.

Here's a sample configuration:

jobs:
  lint:
    runs-on: ubuntu-latest
    timeout-minutes: 5

    steps:
      - name: Run lint
        run: npm run lint
        timeout-minutes: 3

  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Run tests
        run: npm test
        timeout-minutes: 10

  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Build application
        run: npm run build
        timeout-minutes: 10

This example illustrates how job-level and step-level timeouts can be configured independently.

In a real workflow, include the required checkout, runtime setup, and dependency installation steps.

The important point is to give each operation enough time to complete under normal conditions while ensuring that unexpected hangs don't consume resources indefinitely.

If a test consistently requires more time than expected, investigate the reason before simply increasing its timeout.

12. A Practical Optimized GitHub Actions Workflow

Let's put these ideas together into a basic Node.js CI workflow.

This example uses dependency caching, a consistent Node.js version, separate validation jobs, and job-level timeouts.

name: Node.js CI

on:
  push:
    branches: [main]

  pull_request:
    branches: [main]

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

jobs:
  lint:
    name: Lint
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run lint
        run: npm run lint

  test:
    name: Unit tests
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

  build:
    name: Production build
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Build application
        run: npm run build

Before using this workflow, check that Node.js 22 matches your project's supported runtime and that the relevant npm scripts exist.

The example uses major-version tags for GitHub Actions. For security-sensitive production workflows, consider pinning actions to verified full commit SHAs and maintaining a process for reviewing and updating those pins.

What does this workflow improve?

Dependency caching: npm can reuse cached package downloads across compatible workflow runs.

Parallel execution: linting, testing, and building can run independently, reducing elapsed time when runner capacity is available.

Timeout protection: each job has a defined maximum execution time.

Reduced permissions: the workflow receives read-only repository contents permission unless additional permissions are explicitly needed.

Cancellation of obsolete runs: newer commits can replace older CI runs within the same concurrency group.

This is a good starting point, but it isn't automatically the fastest workflow for every project.

For a small application, a single job may be more efficient because it avoids repeated dependency installation.

For a large monorepo, workspace-aware caching and selective testing may offer greater improvements.

The right workflow is the one that provides reliable validation without unnecessary work.

13. How to Measure Whether Your Optimization Worked

After making changes, compare the workflow's performance before and after the optimization.

For example, record the duration of:

  • Dependency installation.

  • Linting.

  • Unit tests.

  • Integration tests.

  • Production builds.

  • Deployment.

Then compare several runs rather than relying on a single result.

Workflow durations can vary because of runner availability, network conditions, cache hits, and external service performance.

A simple table can help:

Operation

Before optimization

After optimization

Dependency installation

2 min 40 sec

55 sec

Linting

15 sec

15 sec

Tests

3 min 20 sec

3 min 20 sec

Build

1 min 50 sec

1 min 50 sec

These numbers are illustrative, not benchmark results.

In this example, dependency caching improves installation time, while the other operations remain unchanged.

If jobs are also moved into parallel execution, the overall elapsed time may decrease further, depending on runner availability and setup overhead.

You should also monitor failure rates.

A workflow that completes quickly but skips necessary tests isn't an improvement.

The goal is to reduce unnecessary waiting while preserving reliable validation and safe deployments.

Conclusion

GitHub Actions timeouts can be frustrating, especially when they interrupt a build or deployment that normally works.

But the best solution isn't always to increase timeout-minutes.

Start by identifying the slowest step and determining whether the problem comes from dependency installation, test execution, build complexity, limited resources, or a process that never finishes.

For Node.js projects, using npm ci, enabling dependency caching through actions/setup-node, avoiding repeated installations, and running independent jobs in parallel are practical places to start.

You can also use step-level timeouts to isolate slow commands, concurrency controls to cancel obsolete CI runs, and better logging to identify bottlenecks.

My recommendation is to measure your workflow before changing it. Optimize the slowest operations first, compare the results, and keep the checks that protect your application.

A well-designed CI pipeline shouldn't just finish quickly. It should provide fast feedback, use resources efficiently, and give you confidence that the code you're deploying has been tested properly.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘