HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

How to cache node_modules folder when using Jenkins Multibranch Pipeline

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
hownode_modulesjenkinsmultibranchcachefolderusingwhenpipeline

Problem

I'm using Jenkins Multibranch Pipeline to handle my CI/CD and I'd like to know if is there a way to cache my node_modules folder?

Every time I push a branch, I execute yarn to install the dependencies. when is master branch, it took 1s to execute this step because it's already cached. Otherwise, when is a new branch, yarn took 2 minutes because is a new environment. Is there a way to cache node_modules globally to be used by all branches/environments?

Solution

It is possible to do this (not with any built-in steps; you essentially have to either use a global cache or write your own caching tool), but I do not recommend it. When I've tried this in the past, I often ran into race conditions. For example, one build would write to the cache while another build simultaneously reads from the cache, or two builds would write to the cache simultaneously, etc. I got a lot of builds with corrupted modules as a result.

Caches do not have these kinds of race conditions when limited to a single job (or in this case, a single branch for a multibranch job) because Jenkins can be configured not to run multiple builds of one job simultaneously. If you take extra steps to ensure that all of the jobs which might access the cache can't run simultaneously, then you could probably get away with a shared cache. But at that point, you're likely to lose the added speed benefit of sharing the cache anyway, since you've massively reduced Jenkins' capacity to run jobs in parallel.

The other scenario where you could get away with a shared cache is if you write to the cache extremely infrequently - and I really do mean extremely. If the cache is rarely written to, then there simply aren't many opportunities for these kinds of race conditions.

Context

StackExchange DevOps Q#8329, answer score: 4

Revisions (0)

No revisions yet.