Clean up resources when VU is spun down


Using the advanced module API, the NewModuleInstance function is called for each VU, so I can make use of NewModuleInstance to initialize any resource that is needed by each VU (such as object instantiations, connections to an external server, etc.).
However, there doesn’t seem to be any corresponding place where I can cleanup resources when a VU is spun down.
What is the recommended approach for cleaning up resources created in NewModuleInstance when VUs are destroyed?

Thank you in advance.

Hi @pcsegal , Welcome to the community forum :tada:

This is currently not supported. You can look at Hooks for extensions - e.g. graceful shutdown, per VU/iteration, etc. · Issue #2432 · grafana/k6 · GitHub for an issue that touches on this.

The workaround that is currently possible is to wait for the context.Done() to be done and do something after that.

There are two problems with that:

  1. The context gets cancelded on each iteration in ordet to signal that it is done. Not on k6 stopping or the scenarion finishing or the VU being destroyed. The last isn’t even like a … operation that is defined within k6.
  2. This will not make k6 wait for you to finish w/e you are doing. So you might not have time to cleanup as the process just finishes.

As an even more hacky workaround you can define and output that will get the Stop() method called, which will wait for you. You then need to communicate this to each ModuleInstance.

Depending on your particular use case there might be other ways.

I will likely be taking a stab at the issue next cycle, but unlikely to have anything for v0.42 , but you are welcome to comment with your particular use case.

As well as any other feedback you have around extension authoring.

Hope this helps you!