Smooth k6.io Performance Testing for Scala Projects with Scala.js
This article looks at writing k6 tests in Scala through Scala.js, and at what that brings: compile-time guarantees, functional composition and direct integration.
Today’s systems seldom break because of one bug. Far more often, they deteriorate under real-world strain: sudden bursts of traffic, chatty calls between services, slow leaks that only show up after hours under load. Performance problems now appear constantly in production rather than during a dedicated testing phase. Cloud environments and SRE-focused observability have moved load validation out of the controlled lab and into the delivery pipeline. If you rely on auto-scaling and dashboards, you only find problems once they are already hurting users in production.
K6 tackles some of these issues by turning performance tests into code: versioned, automated and plugged straight into CI. However, its scripting model is JavaScript-only, which does not suit teams building distributed backends in Scala. You give up type safety, FP patterns*, and the chance to reuse the domain logic and shared libraries that define how the system behaves.
This article explores another route: writing k6 tests in Scala through Scala.js. The runtime model stays the same, and so does the k6 ecosystem. What we gain are compile-time guarantees, functional composition and direct integration into Scala-based projects. Performance testing becomes a first-class part of software engineering rather than the final piece of the puzzle, often handled by a separate team. We can shorten feedback loops, which can complement the widespread “shift-right” approach advocated by DevOps and SRE.
Background
k6 is now among the most popular tools for building performance tests. Developers and QA engineers appreciate how simple, readable and easy to integrate it is.
In the words of the documentation:
Grafana k6 is an extensible, open-source load testing tool built with developers in mind. With k6 you can avoid performance problems and improve reliability proactively.
k6 is a lightweight compiled binary written in GO that embeds the Goja JavaScript interpreter. This design is a deliberate trade-off: it draws on the maturity and familiarity of the JavaScript ecosystem while keeping the low resource usage and efficiency of the Go language. Consequently, test scripts are written in JavaScript – a sensible choice, as both developers and QA engineers know the language well.
Tests can run locally or in a cloud environment with very little boilerplate. K6.io works nicely with Grafana, which allows close to real-time monitoring of test runs. Its extension API lets you use existing community extensions or write your own – for instance, to support custom network protocols.
Why look beyond JavaScript?
JavaScript may be the default for many engineers, particularly those in software quality, but other options deserve attention too. Scala, although known for being complex, provides strong interoperability and a rich feature set that can pay off in performance testing. Teams whose codebase is already in Scala stand to gain a lot.
Here, we will point out both the strengths and the weaknesses Scala brings, so you can judge whether it suits your use case. We will also show how to integrate it with projects built with a few Scala build tools: sbt, mill and Gradle.
Before that, though, a few words about Scala.js, which is what makes all this possible.
Scala.js as a bridge to k6
With Scala.js, we can write Scala applications that compile to JavaScript and run in any modern browser or JavaScript runtime. You can therefore make use of Scala’s static typing and advanced features – functional programming constructs, powerful collections and expressive syntax – while still targeting the JavaScript ecosystem.
In this way, Scala.js can raise code quality and maintainability thanks to stronger type safety and better compiler guarantees. It also lets you reuse existing Scala libraries (to a certain extent) and integrate smoothly with the vast ecosystem of JavaScript libraries. That makes it a powerful link between the JVM world and the JavaScript runtime.
With these foundations laid, we can move on to building a k6 library facade in Scala.js and start prototyping the solution we are aiming for.
The Journey: From Idea to Implementation
Using Scala.js with k6 began with a simple observation: k6 offers an elegant way to write performance tests in JavaScript, yet it felt detached from projects already written in Scala. We wanted to keep using Scala’s type system and tooling while still benefiting from k6’s flexibility and ecosystem.
To check whether this was feasible, we built a simple scala-js project with Scala CLI:
//> using scala "3.5.0"
//> using platform scala-js
package example
import scala.scalajs.js
import scala.scalajs.js.annotation.*
@js.native
object k6 extends js.Object {
def check(response: Response, checks: js.Dictionary[Boolean]): Boolean = js.native
def sleep(response: Int): Unit = sjs.native
}
@js.native
object http extends js.Object {
def get(url: String): Response = js.native
}
@js.native
trait Response extends js.Object {
def body: String = js.native
def status: Int = js.native
}
@JSExportTopLevel(JSImport.Default)
object K6ScalaExample {
@JSExport
def main(): Unit = {
val response = Http.get("https://quickpizza.grafana.com/")
}
}
Once we had proof that the approach works, we built a k6 Grafana facade with ScalaJS, which makes things much simpler:
//> using scala "3.5.0"
//> using platform scala-js
//> using dep "org.scala.js::k6-scala::0.0.1-SNAPSHOT"
package example
import scala.scalajs.js
import scala.scalajs.js.annotation.*
import org.scala.js.k6.http.Http
@JSExportTopLevel(JSImport.Default)
object K6ScalaExample {
@JSExport
def main(): Unit = {
val response = Http.get("https://quickpizza.grafana.com/")
}
}
Integration with Build Tools
That looks good – a fairly tidy implementation. For standalone tests it may even be enough in some cases, but, as we said before, the real payoff comes from integrating it with existing projects. The Scala world has three major build tools: sbt, mill and Gradle. Each of them requires k6 Grafana to be installed.
To confirm that it can be done, we set up a simple project with the right tooling. For SBT, we wrote a simple task:
lazy val root = Project("root", file("."))
.enablePlugins(ScalaJSPlugin)
.settings(
scalaVersion := "3.5.0",
publish / skip := true,
scalaJSLinkerConfig ~= {
_.withModuleSplitStyle(ModuleSplitStyle.FewestModules).withModuleKind(ModuleKind.ESModule)
},
runK6example := {
val jsTargetDir = (Compile / fullOptJS / crossTarget).value
val name = (Compile / fullOptJS / moduleName).value
val jsOutput = jsTargetDir / s"${name}-fastopt.js"
val log = streams.value.log
log.info(s"Using JS output: ${jsOutput.getAbsolutePath()}")
log.info(s"Running k6 test...")
val exitCode = Process(Seq("k6", "run", jsOutput.getAbsolutePath)).!
if (exitCode != 0) {
log.error("k6 failed!")
}
}
)
In the same way, we added a command for mill:
import mill._
import mill.api.Loose
import mill.scalalib._
import mill.scalajslib._
import mill.scalajslib.api._
val projectScalaVersion = "3.5.0"
object helloworld extends ScalaJSModule {
override def scalaVersion = projectScalaVersion
override def scalaJSVersion = "1.18.1"
override def ivyDeps: Target[Loose.Agg[Dep]] = super.ivyDeps() ++ Agg(
ivy"org.scalajs::k6-scala::0.0.1-SNAPSHOT".withDottyCompat(projectScalaVersion)
)
override def moduleKind = ModuleKind.ESModule
override def moduleSplitStyle = ModuleSplitStyle.FewestModules
override def sources = T.sources {
Seq(millSourcePath / "src").map(PathRef(_))
}
def runK6test() = T.command {
val jsFilePath: os.Path = fastLinkJS().dest.path / "main.js"
println(s"Using JS output: $jsFilePath")
val exitCode = os.proc("k6", "run", jsFilePath).call(stdout = os.Inherit, stderr = os.Inherit).exitCode
if (exitCode != 0) {
throw new Exception("k6 failed!")
}
}
}
Performance and Metrics
With a working solution and build tool integrations ready, we wanted to measure how much extra time it might cost compared with “regular” JavaScript. For that we used hyperfine, a tool with a very straightforward syntax:
hyperfine -r 100 -p 'rm -rf .scala-build/ example.js example.js.map' 'scala-cli --power package example.scala --js --js-emit-source-maps --js-module-kind esmodule -f --js-no-opt'
hyperfine -r 100 'k6 run example.js'
hyperfine -r 100 'k6 run pure.js'
hyperfine -r 100 -p 'mill clean' 'mill helloworld.fastOpt'
hyperfine -r 100 -p 'sbt clean' 'sbt fastOptJS'
hyperfine -r 100 -p './gradlew clean' './gradlew link'
hyperfine -r 100 'sbt runK6test'
hyperfine -r 100 'mill runK6test'
hyperfine -r 100 './gradlew runK6test'
Assumptions:
- Compilation time and execution time were measured separately.
- Compilation starts from a clean workspace,
- The script was modified to perform 100 iterations without sending any real requests.
- Only the mean of 100 repetitions is shown.
| technology stack | compilation time | execution time |
|---|---|---|
| k6.io native | N/A | 358.5 ms |
| scala-js with scala-cli | 2.895 s | 467.0 ms |
| scala-js with sbt | 15.214 s | 8.735 s |
| scala-js with mill | 7.402 s | 752.1 ms |
| scala-js with gradle | 10.277 s | 4.313 s |
The numbers show that, even with a clean workspace, compilation adds some overhead relative to the overall test execution time. This example is very simple, and in real-world cases compilation could take longer. Then again, most of the time incremental compilation will be used, which can cut this overhead considerably.
Execution time does differ as well. This may come from the boilerplate code that the Scala.js version generates and how it affects k6’s interpretation performance. Running through build tools adds even more overhead. Still, because typical load tests run for minutes rather than seconds, this overhead should not matter much.
Pros and Cons of Writing k6 Tests in Scala.js
The performance measurements give a clear view of the runtime overhead. Yet execution time is only one of the factors that decide whether Scala.js suits k6 tests. Let’s step back and consider the wider list of pros and cons.
Pros of Writing k6 Tests in Scala.js
- Type safety and IDE support
- Integration with projects based on Scala (and potentially Java)
- The option to reuse domain logic
- Simpler maintenance for teams that already use Scala.
Cons of Writing k6 Tests in Scala.js
- Grafana k6.io offers no native support
- Extra compilation and execution time
- Test failures cannot be traced back to the actual tests
- A smaller community and ecosystem
- A learning curve for Scala.js (if you have not used it before)
- Tests cannot be debugged, though this applies to Grafana k6.io in general.
Summary
Without question, JavaScript is the go-to language for k6. It is the native runtime, broadly used and exceptionally well documented. For most teams, particularly those taking their first steps in performance testing, JavaScript is the quickest route to results with the least setup.
So when is Scala.js worth it?
As noted before, Scala becomes an attractive choice when you already work in a Scala ecosystem – especially in large, type-safe codebases where performance tests have to stay closely in line with existing models or logic.
Apart from that, Scala.js may also suit you well if you:
- Care about type safety to spot problems early and make tests more reliable
- Favour a functional programming style for composing tests and their logic
- Wish to reuse domain logic or data models directly in performance tests
Even so, the current limitations have to be acknowledged: the approach is still at an early stage. It looks promising, but it needs more work before it is fully production-ready – complete API coverage, proper packaging and publishing, better tooling and smooth runtime integration among them.
Links and resources
** JavaScript offers a handful of functional primitives, but with no static types they stay conventions rather than guarantees.*