
Table of Contents
About FIO
FIO is a type-safe, purely functional effect system for F#, designed for building highly concurrent and asynchronous applications. It provides a lightweight DSL for writing composable programs using functional effects.
Inspired by ZIO and Cats Effect, FIO features:
- An IO monad for managing side effects
- Fibers (green threads) for scalable concurrency
- A focus on purity, type safety, and performance
FIO was developed as part of a masterβs thesis in Computer Science at DTU.
Note: FIO is under active development. Contributions, feedback, and questions are welcome.
Please report bugs and request features through GitHub Issues, or contact the maintainer at hey@itsdaniel.dk.
(back to top)
Getting Started
Installation
FIO is distributed as five NuGet packages:
Core Package (Required)
dotnet add package FSharp.FIO
The core package includes:
- Core effect system - FIO monad, fibers, channels, and three runtime implementations
- App framework - FIOApp base classes for simplified application entry points
- Library modules - Console, Clock, Environment, and Random operations
Optional Extension Packages
TCP Sockets
dotnet add package FSharp.FIO.Sockets
Provides TCP socket operations with client, server, and connection pooling functionality.
WebSockets
dotnet add package FSharp.FIO.WebSockets
Provides WebSocket client and server functionality with connection pooling.
HTTP Server (experimental)
dotnet add package FSharp.FIO.Http
Provides composable HTTP server functionality built on ASP.NET Core Kestrel, including routes, handlers, and middleware.
PostgreSQL Database (experimental)
dotnet add package FSharp.FIO.PostgreSQL
Provides PostgreSQL database operations built on Npgsql, including connection pooling, query execution, and transactions.
Quick Start
To get started with FIO:
Core Concepts
Effect Composition
FIO effects are composable values that can be combined using operators, similar to how Result or Option types can be composed in functional programming. These operators enable you to build complex concurrent programs from simple building blocks.
Sequential Composition
Bind Operator (>>=)
The bind operator chains effects sequentially, giving you access to previous results:
// Using computation expression
let getUserData userId =
fio {
let! user = fetchUser userId
let! orders = fetchOrders user.Id
return (user, orders)
}
// Equivalent using >>= operator
let getUserData userId =
fetchUser userId >>= fun user ->
fetchOrders user.Id >>= fun orders ->
FIO.Succeed (user, orders)
Zip Operators (<*>, >, <)
Combine effects sequentially with different result handling:
// <*> - Combine results into tuple
let combined = fetchUser() <*> fetchSettings()
// Returns: FIO<User * Settings, 'E>
// *> - Run both, keep second result
let compute =
Console.PrintLine "Starting computation..."
*> calculateResult()
// Returns: FIO<CalculationResult, 'E>
// <* - Run both, keep first result
let withLogging =
performAction()
<* Console.PrintLine "Action completed!"
// Returns: FIO<ActionResult, 'E>
Parallel Composition
Parallel Zip (<&>)
Execute effects concurrently and wait for both to complete:
// Execute two effects in parallel
let fetchUserAndOrders userId =
fetchUser userId <&> fetchOrders userId
<!> fun (user, orders) ->
{ User = user; Orders = orders }
// Both fetches run concurrently
// Multiple parallel API calls
let dashboard =
getProfile() <&> getNotifications() <&> getActivity()
<!> fun ((profile, notifications), activity) ->
{ Profile = profile
Notifications = notifications
Activity = activity }
Parallel Operators (&>, <&, <&&>)
// &> - Run in parallel, keep second result
let warmupThenCompute = warmupCache() &> calculateResult()
// <& - Run in parallel, keep first result
let computeWithBackground = calculateResult() <& logMetrics()
// <&&> - Run in parallel, discard both results
let fireAndForget =
sendEmail() <&&> updateMetrics() <&&> logActivity()
// All run concurrently, returns FIO<unit, 'E>
Error Handling
OrElse Operator (<|>)
Try the first effect, fallback to the second if it fails:
// Simple fallback
let fetchData = fetchFromCache() <|> fetchFromDatabase()
// Chain multiple fallbacks
let robustFetch =
fetchFromPrimary()
<|> fetchFromSecondary()
<|> fetchFromCache()
<|> FIO.Succeed(defaultValue)
Map Operator (<!>)
Transform the success value without affecting errors:
// Transform a single value
let doubled = computeValue() <!> fun x -> x * 2
// Chain transformations
let pipeline =
fetchNumber()
<!> fun n -> n * 2
<!> fun n -> n + 10
<!> fun n -> $"Result: {n}"
Computation Expressions vs Operators
Use computation expressions for complex logic with branching, loops, or multiple let bindings:
let processOrders = fio {
let! orders = fetchOrders()
let mutable processed = 0
for order in orders do
if order.Total > 100.0 then
do! applyDiscount order
do! processOrder order
processed <- processed + 1
return processed
}
Use operators for simple pipelines and functional composition:
let pipeline =
fetchData()
<!> validateData
>>= enrichData
>>= saveData
<* Console.PrintLine "Pipeline completed!"
Operator Quick Reference
>>= | Sequential | Result of function | Chain with access to previous value |
<*> | Sequential | Tuple | Combine two results |
*> | Sequential | Second | Side effect then main result |
<* | Sequential | First | Main result then side effect |
<&> | Parallel | Tuple | Concurrent execution |
&> | Parallel | Second | Concurrent, prefer second |
<& | Parallel | First | Concurrent, prefer first |
<&&> | Parallel | Unit | Fire-and-forget parallel tasks |
<|> | Sequential | First success | Error recovery with fallback |
<!> | N/A | Transformed | Map over success value |
For more examples of operator usage, see FSharp.FIO.Examples.
Usage
You can use FIO in two ways:
Direct Usage
Create a new F# file and open the DSL, IO and Concurrent runtime modules:
module DirectUsage
open FSharp.FIO.DSL
open FSharp.FIO.Console
open FSharp.FIO.Runtime.Default
[<EntryPoint>]
let main _ =
let askForName = fio {
do! Console.PrintLine "Hello! What is your name?"
let! name = Console.ReadLine
do! Console.PrintLine $"Hello, {name}! Welcome to FIO! πͺ»π"
}
let fiber = (new DefaultRuntime()).Run askForName
fiber.UnsafePrintResult()
0
Run it with:
$ dotnet run
And you'll see the following output:
Hello! What is your name?
Daniel
Hello, Daniel! Welcome to FIO! πͺ»π
Succeeded ()
Using FIOApp (Recommended)
FIOApp provides a high-level framework for running FIO effects with lifecycle management, shutdown hooks, and automatic exit codes. It comes in three variants to suit different needs.
FIOApp Variants
FIOApp comes in three variants to suit different needs:
1. SimpleFIOApp
SimpleFIOApp is a type alias for FIOApp<unit, exn>, used when your effect performs actions without returning a meaningful result.
// SimpleFIOApp = FIOApp<unit, exn>
type WelcomeApp() =
inherit SimpleFIOApp()
override _.effect = fio {
do! Console.PrintLine "Hello! What is your name?"
let! name = Console.ReadLine
do! Console.PrintLine $"Hello, {name}! Welcome to FIO! πͺ»π"
}
2. DefaultFIOApp<'R>
DefaultFIOApp<'R> is a type alias for FIOApp<'R, exn>, used when you need to return a specific value but use standard exceptions for errors.
// DefaultFIOApp<'R> = FIOApp<'R, exn>
type RandomNumberApp() =
inherit DefaultFIOApp<int>()
override _.effect = fio {
let! randomNumber = FIO.Attempt(fun () -> Random().Next(1, 100))
do! Console.PrintLine $"Generated: {randomNumber}"
return randomNumber // Returns int
}
3. FIOApp<'R, 'E>
The generic FIOApp<'R, 'E> base class provides full control over both result and error types, enabling type-safe domain-specific error handling.
type AppError =
| ValidationError of string
| NotFound
| DatabaseError of string
type UserLookupApp() =
inherit FIOApp<string, AppError>()
override _.effect = fio {
do! Console.Print "Enter user ID: "
let! userId = Console.ReadLine
if userId = "" then
return! FIO.Fail(ValidationError "User ID cannot be empty")
else
return $"User: {userId}"
}
// Optional: Override exit code mappings
override _.exitCodeError = function
| ValidationError _ -> 2
| NotFound -> 3
| DatabaseError _ -> 4
Choosing Your Variant
- Use SimpleFIOApp when your effect returns
unit and uses standard exceptions (most CLI apps)
- Use DefaultFIOApp<'R> when you need a custom result type but standard exceptions
- Use FIOApp<'R, 'E> when you need custom error types for domain-specific error handling
FIOApp Customization
FIOApp supports extensive customization through overridable properties:
type MyApp() =
inherit SimpleFIOApp()
// Application metadata
override _.name = "My Application"
override _.version = "1.0.0"
override _.description = "A sample FIO application"
// Show startup banner
override _.showBanner = true
// Cleanup on shutdown (Ctrl+C or completion)
override _.shutdownHook() = fio {
do! Console.PrintLine "Cleaning up resources..."
}
// Custom runtime configuration
override _.runtime =
new ConcurrentRuntime { EWC = 8; EWS = 500; BWC = 2 }
override _.effect = fio { ... }
Available customizations:
- Metadata:
name, version, description, showBanner, banner
- Lifecycle:
shutdownHook(), shutdownHookTimeout, onStart(), onSuccess(), onError()
- Runtime:
runtime, configureThreadPool()
- Exit codes:
exitCodeSuccess, exitCodeError, exitCodeFatalError
For more examples, see FSharp.FIO.Examples.App.
Alternative: DSL-Only Style
Prefer DSL chaining? Use bind (>>=) directly:
module DSLOnly
open FSharp.FIO.DSL
open FSharp.FIO.Console
open FSharp.FIO.Runtime.Default
let askForName =
Console.PrintLine "Hello! What is your name?" >>= fun _ ->
Console.ReadLine >>= fun name ->
Console.PrintLine $"Hello, {name}! Welcome to FIO! πͺ»π"
[<EntryPoint>]
let main _ =
let fiber = (new DefaultRuntime()).Run askForName
fiber.UnsafePrintResult()
0
Library Modules
The core package includes four library modules for common effectful operations. All modules use qualified access (e.g., Console.PrintLine).
Console
Provides functional console I/O operations including input/output, colors, cursor control, and more.
open FSharp.FIO.Console
let effect = fio {
do! Console.PrintLine "Enter your name:"
let! name = Console.ReadLine
do! Console.PrintLine $"Hello, {name}!"
// Read password with masked input
do! Console.Print "Password: "
let! password = Console.ReadPassword
// Colored output (automatically restores original color)
do! Console.WithForegroundColor(ConsoleColor.Green,
Console.PrintLine "Success!")
}
Key functions:
- I/O:
Print, PrintLine, ReadLine, ReadKey, ReadPassword
- Stderr:
PrintError, PrintErrorLine, WriteError, WriteErrorLine
- Colors:
SetForegroundColor, SetBackgroundColor, WithForegroundColor, WithColors
- Cursor:
SetCursorPosition, GetCursorPosition, Clear
- Properties:
GetTitle, SetTitle, GetWindowWidth, GetWindowHeight
Clock
Provides time and date operations including timestamps and performance measurement.
open FSharp.FIO.Clock
let effect = fio {
let! now = Clock.Now()
let! utcNow = Clock.UtcNow()
// Unix timestamps
let! timestamp = Clock.Timestamp() // seconds
let! timestampMs = Clock.TimestampMillis() // milliseconds
// Measure execution time
let! (result, elapsed) = Clock.Timed(someExpensiveOperation)
do! Console.PrintLine $"Completed in {elapsed.TotalMilliseconds}ms"
}
Key functions:
- Time queries:
Now(), UtcNow(), Today(), NowOffset(), UtcNowOffset()
- Timestamps:
Timestamp(), TimestampMillis(), ToTimestamp, FromTimestamp
- Measurement:
Timed(effect), GetTimestamp(), GetElapsedTime(start, end)
Environment
Provides environment variable access and system information.
open FSharp.FIO.Environment
let effect = fio {
// Environment variables with defaults
let! port = Environment.GetOrDefault("PORT", "8080")
let! debug = Environment.GetBoolOrDefault("DEBUG", false)
let! timeout = Environment.GetIntOrDefault("TIMEOUT", 30)
// System information
let! user = Environment.UserName()
let! machine = Environment.MachineName()
let! cwd = Environment.CurrentDirectory()
// Check if variable is set
let! hasToken = Environment.IsSet "API_TOKEN"
}
Key functions:
- Env vars:
GetOption, Get, GetOrDefault, GetAll, IsSet
- Typed access:
GetInt, GetIntOrDefault, GetBool, GetBoolOrDefault
- System info:
MachineName(), UserName(), CurrentDirectory(), GetTempPath()
- Constants:
ProcessorCount, Is64BitProcess, Is64BitOperatingSystem, NewLine
Random
Provides random number generation with thread-safe operations.
open FSharp.FIO.Random
let effect = fio {
// Integers
let! roll = Random.NextIntRange(1, 7) // Dice roll [1, 6]
let! bigRoll = Random.NextInt64Range(1L, 1000000L)
// Floating point
let! probability = Random.NextDouble() // [0.0, 1.0)
let! temperature = Random.NextDoubleRange(-10.0, 40.0)
// Utilities
let! coinFlip = Random.NextBool()
let! guid = Random.NextGuid()
let! bytes = Random.NextBytes(32)
// Collections
let! shuffled = Random.Shuffle [1; 2; 3; 4; 5]
let! picked = Random.Choice ["red"; "green"; "blue"]
}
Key functions:
- Integers:
NextInt(), NextIntBounded(max), NextIntRange(min, max), NextInt64...
- Floats:
NextDouble(), NextDoubleBounded(max), NextDoubleRange(min, max)
- Utilities:
NextBool(), NextGuid(), NextBytes(count)
- Collections:
Shuffle(list), Choice(list), ChoiceOrFail(list, onEmpty)
Extension Packages
FIO provides optional packages for common scenarios:
HTTP Server
Build HTTP servers with composable routes and middleware:
open FSharp.FIO.Http
open FSharp.FIO.Http.RoutesOperators
open FSharp.FIO.Http.MiddlewareOperators
// Define handlers
let helloHandler : HttpHandler<exn> =
HttpHandler.text "Hello from FIO!"
let jsonHandler : HttpHandler<exn> =
HttpHandler.okJson {| message = "JSON response" |}
// Compose routes
let routes =
GET "/" helloHandler
++ GET "/json" jsonHandler
// Run server
let config = ServerConfig.defaultConfig // localhost:8080
Server.runServer config routes
For complete examples, see FSharp.FIO.Examples.Http.
PostgreSQL
Connect to PostgreSQL databases with connection pooling:
open FSharp.FIO.PostgreSQL
// Configure connection pool
let config = {
ConnectionString = "Host=localhost;Database=mydb;Username=user;Password=pass"
MinPoolSize = 5
MaxPoolSize = 20
ConnectionLifetime = 300
CommandTimeout = 30
}
let pool = Pool.create config
// Query with parameters
let getUserById id = fio {
let sql = "SELECT id, name, email FROM users WHERE id = @id"
let parameters = ["id" @= id]
return! Dsl.queryFirstWithParams sql parameters userMapper pool
}
For complete examples, see FSharp.FIO.Examples.PostgreSQL.
TCP Sockets
TCP socket client and server functionality. See FSharp.FIO.Sockets for documentation.
WebSockets
WebSocket client and server functionality. See FSharp.FIO.WebSockets for documentation.
Benchmarks
This repository includes five benchmarks, each designed to evaluate a specific aspect of concurrent computation. All benchmarks are adapted from the Savina β An Actor Benchmark Suite.
Benchmark Overview
Pingpong β Message sending and retrieval between two actors
Threadring β Message passing with frequent fiber context switching
Big β Many-to-many message passing with high channel contention
Bang β Many-to-one messaging, stressing a single receiver
Fork β Measures fiber spawning overhead
Running Benchmarks
The benchmarks accept a variety of command-line options:
USAGE: FSharp.FIO.Benchmarks [--help]
[--direct-runtime]
[--cooperative-runtime <ewc> <ews> <bwc>]
[--concurrent-runtime <ewc> <ews> <bwc>]
[--runs <runs>]
[--actor-increment <actorInc> <times>]
[--round-increment <roundInc> <times>]
[--pingpong <roundCount>]
[--threadring <actorCount> <roundCount>]
[--big <actorCount> <roundCount>]
[--bang <actorCount> <roundCount>]
[--fork <actorCount>]
[--save <saveToCsv>]
[--savepath <absolutePath>]
OPTIONS:
--direct-runtime specify Direct runtime
--cooperative-runtime <ewc> <ews> <bwc>
specify Cooperative runtime with ewc, ews and bwc
--concurrent-runtime <ewc> <ews> <bwc>
specify Concurrent runtime with ewc, ews and bwc
--runs <runs> specify number of runs for each benchmark
--actor-increment <actorInc> <times>
specify the value of actor increment and the number of times
--round-increment <roundInc> <times>
specify the value of round increment and the number of times
--pingpong <roundCount>
specify number of rounds for Pingpong benchmark
--threadring <actorCount> <roundCount>
specify number of actors and rounds for Threadring benchmark
--big <actorCount> <roundCount>
specify number of actors and rounds for Big benchmark
--bang <actorCount> <roundCount>
specify number of actors and rounds for Bang benchmark
--fork <actorCount> specify number of actors for Fork benchmark
--save <saveToCsv> should save benchmark results to csv file
--savepath <absolutePath>
specify absolute path to save the benchmark results csv file
--help display this list of options.
Example
To run each benchmark 30 times using the concurrent runtime (39 evaluation workers, 200 evaluation steps, 1 blocking worker):
--concurrent-runtime 39 200 1 --runs 30 --pingpong 150000 --threadring 10000 10 --big 250 10 --bang 10000 10 --fork 20000
Experimental Flags
FIO also supports optional compile-time flags:
Note: These features are experimental and may behave unpredictably.
Performance
The following plots illustrate the execution time (measured in milliseconds) and scalability of the available runtime systems across benchmarks.
The runtimes differ in how they manage fibers and blocked operations:
- Direct β .NET tasks with waiting for blocked fibers
- Cooperative β Fibers with linear-time handling of blocked fibers
- Concurrent β Fibers with constant-time handling of blocked fibers
Execution Time
The boxplots show the measured execution time for each benchmark with the shown benchmark and runtime configurations.
Scalability
The lineplots show for each benchmark, how each runtime scales when the amount of fibers increases.
Roadmap
See the open issues for a full list of proposed features (and known issues).
(back to top)
Contributing
We welcome contributions! To contribute:
- Star the repository
- Open an issue (tag it with
enhancement)
- Fork the project and submit a pull request
Contributing Guide
- Fork the repository
- Create a branch:
git checkout -b feature/AmazingFeature
- Commit your changes:
git commit -m 'Add AmazingFeature'
- Push the branch:
git push origin feature/AmazingFeature
- Open a pull request
Top contributors
(back to top)
License
Distributed under the MIT License. See LICENSE.md for more information.
(back to top)
Contact
Daniel Larsen (itsdaniel.dk)
(back to top)
Acknowledgments
Alceste Scalas (people.compute.dtu.dk)
(back to top)