• Stars
    star
    1,817
  • Rank 25,552 (Top 0.6 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The pure asynchronous runtime for Scala

Cats Effect

Latest version Discord

Cats Effect is a high-performance, asynchronous, composable framework for building real-world applications in a purely functional style within the Typelevel ecosystem. It provides a concrete tool, known as "the IO monad", for capturing and controlling actions, often referred to as "effects", that your program wishes to perform within a resource-safe, typed context with seamless support for concurrency and coordination. These effects may be asynchronous (callback-driven) or synchronous (directly returning values); they may return within microseconds or run infinitely.

Even more importantly, Cats Effect defines a set of typeclasses which define what it means to be a purely functional runtime system. These abstractions power a thriving ecosystem consisting of streaming frameworks, JDBC database layers, HTTP servers and clients, asynchronous clients for systems like Redis and MongoDB, and so much more! Additionally, you can leverage these abstractions within your own application to unlock powerful capabilities with little-or-no code changes, for example solving problems such as dependency injection, multiple error channels, shared state across modules, tracing, and more.

Getting Started

  • Wired: 3.5.4
  • Tired: 2.5.5 (end of life)
libraryDependencies += "org.typelevel" %% "cats-effect" % "3.5.4"

The above represents the core, stable dependency which brings in the entirety of Cats Effect. This is most likely what you want. All current Cats Effect releases are published for Scala 2.12, 2.13, 3.0, and Scala.js 1.7.

Or, if you prefer a less bare-bones starting point, you can try the Giter8 template:

$ sbt new typelevel/ce3.g8

Depending on your use-case, you may want to consider one of the several other modules which are made available within the Cats Effect release. If you're a datatype implementer (like Monix), you probably only want to depend on kernel (the typeclasses) in your compile scope and laws in your test scope:

libraryDependencies ++= Seq(
  "org.typelevel" %% "cats-effect-kernel" % "3.5.4",
  "org.typelevel" %% "cats-effect-laws"   % "3.5.4" % Test)

If you're a middleware framework (like Fs2), you probably want to depend on std, which gives you access to Queue, Semaphore, and much more without introducing a hard-dependency on IO outside of your tests:

libraryDependencies ++= Seq(
  "org.typelevel" %% "cats-effect-std" % "3.5.4",
  "org.typelevel" %% "cats-effect"     % "3.5.4" % Test)

You may also find some utility in the testkit and kernel-testkit projects, which contain TestContext, generators for IO, and a few other things:

libraryDependencies += "org.typelevel" %% "cats-effect-testkit" % "3.5.4" % Test

Cats Effect provides backward binary compatibility within the 2.x and 3.x version lines, and both forward and backward compatibility within any major/minor line. This is analogous to the versioning scheme used by Cats itself, as well as other major projects such as Scala.js. Thus, any project depending upon Cats Effect 2.2.1 can be used with libraries compiled against Cats Effect 2.0.0 or 2.2.3, but not with libraries compiled against 2.3.0 or higher.

Updating from Cats Effect 1.x / 2.x

Check out the migration guide!

Hello, World

import cats.effect._

object Main extends IOApp.Simple {
  val run = IO.println("Hello, World!")
}

Or, if you need the ability to take arguments and return exit codes:

import cats.effect._

object Main extends IOApp {
  def run(args: List[String]): IO[ExitCode] =
    if (args.headOption.map(_ == "--do-it").getOrElse(false))
      IO.println("I did it!").as(ExitCode.Success)
    else
      IO.println("Didn't do it").as(ExitCode(-1))
}

Five Simple Rules

Any program written using Cats Effect provides incredibly strong guarantees and powerful functionality, performance, safety, and composability, provided you follow each of the following rules:

  • Wrap all side-effects in delay, async, blocking, or interruptible/interruptibleMany
    • (pro tip: try to keep the size of your delay blocks small; two delays with a flatMap is much better than one big delay)
  • Use bracket or Resource for anything which must be closed
  • Never hard-block a thread outside of blocking or interruptible/interruptibleMany
  • Use IOApp instead of writing your own def main
  • Never call anything that has the word unsafe in the name

If you follow these rules, and you use libraries and frameworks which also follow these rules, you will get a truly astonishing array of things essentially for free:

  • Extremely high performance, elastic, and scalable applications
  • Proven backpressure mechanisms under extreme load in real deployments
  • Reliable resource safety in all cases
  • Aggressive interruption of unnecessary work (e.g. timeouts), automatically, without any extra implementation effort
  • Composable and modular application architecture (real, practical functional programming)
  • Simple, safe, and incredibly powerful concurrency mechanisms that get faster under high contention
  • Highly tuned application runtime with optimized threading and memory management semantics
  • Powerful and orthogonal abstractions which enable architectural decomposition that scales to any problem space
  • Access to an entire ecosystem of uniquely powerful libraries and tooling
  • โ€ฆand so much more

Performance

a bar chart showing 'Fixed Thread Pool' and 'Cats Effect 3', with the latter being substantially taller than the former

Most functional and async frameworks will tout their performance on synthetic microbenchmarks, measuring things like how many flatMaps they can evaluate per microsecond and so on. However, most programs aren't just a bunch of flatMaps, and the true performance bottlenecks are usually in things like contention scaling under high load, memory and other resource management, backpressure, page faults, and such. In these areas, Cats Effect is truly unrivaled on the JVM, and in most cases, applications written in a purely functional style using Cats Effect will exceed the performance and elasticity of the same applications written in an imperative style.

The chart to the right shows the results of a synthetic benchmark simulating an extremely high-contention scheduling scenario. The scenario is typical of something like a microservice handling extremely high requests-per-second, with each request representing some sort of scatter/gather semantic in which many complex asynchronous actions must be taken in parallel to produce a timely response.

The benchmark measures the performance of a typical "disruptor pattern" application written using a fixed thread pool (from java.util.concurrent.Executors) compared to the same workflow implemented using Cats Effect (specifically version 3.0). The scores are not a typo: Cats Effect is almost 55x faster than the typical disruptor-style, hand-tuned implementation. Similarly dramatic results are consistently observed when comparing Cats Effect with other popular asynchronous and functional frameworks.

As always, benchmarks are one thing, and your application is its own special snowflake with its own performance profile. Always measure and test your application before assuming that someone else's performance results apply in your use-case. When in doubt, come talk with us and we'll give you an honest opinion!

Abstraction

the cats effect hierarchy of typeclasses as of version 3.0

Cats Effect isn't just designed to enable high performance applications with out-of-the-box safety and elasticity under load. It was intended first and foremost as a tool for implementing composable and reasonable software that is easy to write, easy to test, and easy to evolve as your team and requirements change over time. To achieve this goal, Cats Effect embraces and enables strong, typeful, purely-functional programming styles that are uniquely tailored for the Scala language.

The typical Cats Effect system is often built in terms of simple, orthogonal, primitive capabilities which come together to represent all the expressive power necessary to encode a modern asynchronous runtime. Much like how the rules of addition, multiplication, and integers come together to define much of what we understand about basic arithmetic, so too do the rules of Functor, Monad, and Concurrent come together to define the nature of a program which has all the capabilities you need.

By learning and leveraging these capabilities directly, it is possible to write functions and classes which clearly state their requirements and capabilities in a statically typed and discoverable fashion, improving documentation, readability, and separation of concerns.

And, just as with arithmetic, even when you don't directly leverage the nature of abstract mathematics in your daily life, those laws are still present shaping the world around you and enabling powerful and surprising things like computers and trains and restaurant menus. The laws and abstractions of Cats Effect support a powerful and unique ecosystem of frameworks, giving you access to rich and advanced functionality unparalleled in any language or ecosystem, battle tested in production environments ranging from some of the largest companies in the world to some of the nimblest startups.

Contributing

Please see CONTRIBUTING.md for more details. Lots to do!

Website

To build the documentation site locally, the following dependencies are needed, in addition to sbt.

  • Node (14.x ideally)
  • Yarn (any version should work)

NOTE: Nix users can just run nix-shell at the root directory and follow along the next instructions.

Next, check out the documentation branch along with its submodules.

git checkout --track origin/docs
git submodule update --init --recursive

Finally, build the site.

./build.sh host

If everything goes well, your browser will open at the end of this.

Tool Sponsorship

Development of Cats Effect is generously supported in part by YourKit through the use of their excellent Java profiler.

License

Copyright 2017-2024 Typelevel

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

cats

Lightweight, modular, and extensible library for functional programming.
Scala
5,182
star
2

fs2

Compositional, streaming I/O library for Scala
Scala
2,359
star
3

doobie

Functional JDBC layer for Scala.
Scala
2,161
star
4

scalacheck

Property-based testing for Scala
Scala
1,908
star
5

spire

Powerful new number types and numeric abstractions for Scala.
Scala
1,761
star
6

skunk

A data access library for Scala + Postgres.
Scala
1,579
star
7

simulacrum

First class syntax support for type classes in Scala
Scala
937
star
8

squants

The Scala API for Quantities, Units of Measure and Dimensional Analysis
Scala
922
star
9

kind-projector

Compiler plugin for making type lambdas (type projections) easier to write
Scala
915
star
10

frameless

Expressive types for Spark.
Scala
879
star
11

cats-collections

Data structures for pure functional programming in Scala
Scala
557
star
12

kittens

Automatic type class derivation for Cats
Scala
531
star
13

jawn

Jawn is for parsing jay-sawn (JSON)
Scala
431
star
14

log4cats

Logging Tools For Interaction with cats-effect
Scala
400
star
15

Laika

Site and E-book Generator and Customizable Text Markup Transformer for sbt, Scala and Scala.js
Scala
387
star
16

algebra

Experimental project to lay out basic algebra type classes
Scala
378
star
17

mouse

A small companion to cats
Scala
365
star
18

sbt-tpolecat

scalac options for the enlightened
Scala
328
star
19

discipline

Flexible law checking for Scala
Scala
328
star
20

natchez

functional tracing for cats
Scala
324
star
21

cats-tagless

Library of utilities for tagless final encoded algebras
Scala
314
star
22

cats-mtl

cats transformer type classes.
Scala
308
star
23

CT_from_Programmers.scala

Scala sample code for Bartosz Milewski's CT for Programmers
Scala
279
star
24

fs2-grpc

gRPC implementation for FS2/cats-effect
Scala
270
star
25

cats-parse

A parsing library for the cats ecosystem
Scala
233
star
26

machinist

Spire's macros for zero-cost operator enrichment
Scala
191
star
27

cats-effect-testing

Integration between cats-effect and test frameworks
Scala
191
star
28

shapeless-3

Generic programming for Scala
Scala
185
star
29

paiges

an implementation of Wadler's a prettier printer
Scala
183
star
30

grackle

Grackle: Functional GraphQL for the Typelevel stack
Scala
176
star
31

sbt-typelevel

Let sbt work for you.
Scala
170
star
32

munit-cats-effect

Integration library for MUnit & cats-effect
Scala
149
star
33

feral

Feral cats are homeless, feral functions are serverless
Scala
144
star
34

catbird

Birds and cats together
Scala
139
star
35

otel4s

An OpenTelemetry library for Scala based on Cats-Effect
Scala
138
star
36

fs2-chat

Sample project demonstrating use of fs2-io to build a chat client and server
Scala
123
star
37

spotted-leopards

Proof of concept for a cats-like library built using Dotty features
Scala
112
star
38

fabric

Object-Notation Abstraction for JSON, binary, HOCON, etc.
Scala
110
star
39

literally

Compile time validation of literal values built from strings
Scala
106
star
40

toolkit

Quickstart your next app with the Typelevel Toolkit!
Scala
94
star
41

cats-time

Cats Instances for Java Time
Scala
91
star
42

typelevel-nix

Development tools for Typelevel projects
Nix
87
star
43

cats-effect-cps

An incubator project for async/await syntax support for Cats Effect
Scala
81
star
44

vault

Type-safe, persistent storage for values of arbitrary types
Scala
81
star
45

shapeless-contrib

Interoperability libraries for Shapeless
Scala
79
star
46

scalacheck-effect

Effectful property testing built on ScalaCheck
Scala
76
star
47

coop

Cooperative multithreading as a pure monad transformer
Scala
68
star
48

claimant

Library to support automatic labeling of ScalaCheck properties.
Scala
68
star
49

typeclassic

Everything you need to make type classes first class.
Scala
61
star
50

scalaz-contrib

Interoperability libraries & additional data structures and instances for Scalaz
Scala
55
star
51

twiddles

Micro-library for building effectful protocols
Scala
55
star
52

monoids

Generic Monoids for Scala
Scala
51
star
53

fs2-netty

What it says on the tin!
Scala
47
star
54

sbt-catalysts

sbt utilities for open source projects
Scala
45
star
55

natchez-http4s

Glorious integration layer for Natchez and Http4s.
Scala
44
star
56

typelevel.github.com

Web site of typelevel.scala
HTML
40
star
57

jawn-fs2

Integration between jawn and fs2
Scala
38
star
58

keypool

A Keyed Pool Implementation for Scala
Scala
34
star
59

scalaz-specs2

Specs2 bindings for Scalaz
Scala
34
star
60

catalysts

Scala
34
star
61

simulacrum-scalafix

Simulacrum as Scalafix rules
Scala
34
star
62

case-insensitive

A case-insensitive string for Scala
Scala
34
star
63

scalaz-outlaws

outcasts no longer allowed in the ivory tower
Scala
28
star
64

bobcats

Typelevel's very own CryptoKitties!
Scala
28
star
65

scalac-options

A library for configuring scalac options
Scala
27
star
66

weaver-test

A test framework that runs everything in parallel.
Scala
27
star
67

ce3.g8

Scala
24
star
68

scalaz-scalatest

Scalatest bindings for scalaz.
Scala
23
star
69

general

Repository for general Typelevel information, activity and issues
19
star
70

discipline-munit

MUnit binding for Typelevel Discipline
Scala
18
star
71

cats-testkit-scalatest

Cats Testkit for Scalatest
Scala
18
star
72

unique

Unique Functional Values for Scala
Scala
17
star
73

discipline-scalatest

ScalaTest binding for Discipline
Scala
17
star
74

typelevel-scalafix

Scalafix rules for Typelevel projects
Scala
17
star
75

semigroups

Scala
16
star
76

cats-effect-shell

Command line debugging console for Cats Effect
Scala
15
star
77

jdk-index

A Jabba compatible index of JDK versions
Scala
14
star
78

cats-uri

URI implementation based on cats-parse with cats instances
Scala
14
star
79

typelevel.g8

A typelevel.g8 based on sbt-typelevel
Scala
14
star
80

catapult

Scala
13
star
81

discipline-specs2

Specs2 Integration for Discipline
Scala
9
star
82

governance

Typelevel governance
Scala
7
star
83

catz-cradle

Testbed for scala libraries and tools, based on examples from cats docs
Scala
7
star
84

spire-contrib

Interoperability libraries for spire
Shell
7
star
85

idna4s

Cross-platform Scala implementation of Internationalized Domain Names in Applications
Scala
7
star
86

scalac-compat

Lightweight tools for tackling Scalac version incompatibilities
Scala
6
star
87

steward

Runs Scala Steward for Typelevel projects
5
star
88

cats-effect-main

3
star
89

sacagawea

Common infrastructure for tracing functional effects
Scala
3
star
90

scalacheck-xml

Scalacheck instances for scala-xml
Scala
3
star
91

sorcery

WIP
2
star
92

scalacheck-web

ScalaCheck Web Site
Nix
2
star
93

sbt-catalysts.g8

Scala
2
star
94

feral.g8

Giter8 template for feral serverless
Scala
2
star
95

download-java

2
star
96

toolkit.g8

A Giter8 template for Typelevel Toolkit!
Scala
2
star
97

sbt-tls-crossproject

sbt-crossproject plugin for Typelevel Scala
Scala
1
star
98

await-cirrus

Depend on Cirrus CI from a GitHub Actions workflow
JavaScript
1
star
99

catalysts-docker

Shell
1
star
100

.github

a โœจspecial โœจ repository for project defaults and organization readme
1
star