Learn Fiber · 12/14

Performance and Optimization

7 min read

Performance and Optimization in Fiber 🏎️💨

Welcome, intrepid developer! You've built your Fiber application, and it's working. But is it fast? Is it resilient? Can it handle the chaotic whirlwind of the internet? This guide will equip you with the knowledge to turbocharge your Fiber app, making it faster, more stable, and ready for anything.


1. Caching Responses to Improve Speed ⚡

The Problem: Imagine you have a very popular blog post. Every time a user visits, your server has to fetch the same post from the database, process it, and send it back. This is like a librarian fetching the same popular book from the shelf over and over again for hundreds of people in a line. It's repetitive and slow!

The Solution: Caching! Caching is the process of storing copies of responses in a temporary storage location, or "cache." When the same request comes in again, we can serve the copy from the cache instead of regenerating it from scratch. It's like the librarian keeping a copy of the popular book right at the front desk for quick access.

With Fiber, we can use the Cache middleware to handle this automatically.

Getting Started with Caching

First, you need to install the middleware. Let's get our tools ready!

bash
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/storage/memory/v2
go get -u github.com/gofiber/fiber/v2/middleware/cache

Hands-On Example

Let's see it in action. We'll create a simple server that caches a response for a few seconds.

go
package main

import (
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cache"
	"github.com/gofiber/storage/memory/v2"
)

func main() {
	app := fiber.New()

	// Initialize a new storage provider
	storage := memory.New()

	// Use the cache middleware
	app.Use(cache.New(cache.Config{
		// Cache requests for 5 seconds
		Expiration:   5 * time.Second,
		// The storage provider to use
		Storage:      storage,
		// Define which requests to cache (e.g., only GET requests)
		Next: func(c *fiber.Ctx) bool {
			return c.Request().Header.Get("No-Cache") != ""
		},
	}))

	app.Get("/hello", func(c *fiber.Ctx) error {
		// This response will be cached for 5 seconds
		return c.SendString("Hello, World! The time is " + time.Now().String())
	})

	app.Listen(":3000")
}

What's happening here?

  1. We import the necessary packages, including the cache middleware and a memory storage provider.
  2. We initialize a new in-memory storage. For production, you might want to use something more persistent like Redis.
  3. We tell our Fiber app to Use the cache middleware.
  4. We configure it to cache responses for 5 seconds.
  5. The Next function allows us to specify which requests shouldn't be cached. Here, we're skipping the cache if a request has a "No-Cache" header.
  6. Now, if you run this and visit /hello, the time will stay the same for 5 seconds, no matter how many times you refresh! Magic! ✨

Fun Fact: The term "cache" comes from the French word "cacher," which means "to hide." So, we're essentially hiding a copy of the response for quick retrieval!


2. Rate Limiting: Protecting Your API 🛡️

The Problem: Your API is a huge success! So huge, in fact, that a single user (or a malicious bot) is sending thousands of requests per second, overloading your server and making it unavailable for everyone else. This is like one person trying to order 1,000 coffees at once during the morning rush, blocking the line for everyone.

The Solution: Rate Limiting. Rate limiting restricts the number of requests a user can make in a given time frame. It’s like telling the coffee enthusiast, "Hey, you can have 5 coffees every 10 minutes, but that's it. Let others have a turn!"

Fiber's Limiter middleware makes this incredibly easy.

Getting Started with Rate Limiting

Let's get the middleware installed.

bash
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/fiber/v2/middleware/limiter

Hands-On Example

Here's how to set up a basic rate limiter.

go
package main

import (
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/limiter"
)

func main() {
	app := fiber.New()

	// Use the limiter middleware
	app.Use(limiter.New(limiter.Config{
		// Allow a maximum of 3 requests every 10 seconds
		Max:        3,
		Expiration: 10 * time.Second,
		KeyGenerator: func(c *fiber.Ctx) string {
			return c.IP() // Limit by IP address
		},
		LimitReached: func(c *fiber.Ctx) error {
			return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{
				"message": "Whoa, slow down there, buddy! 🤠",
			})
		},
	}))

	app.Get("/api/data", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{
			"data": "Here is your precious data!",
		})
	})

	app.Listen(":3000")
}

What's happening here?

  1. We apply the limiter middleware to our app.
  2. Max: 3 and Expiration: 10 * time.Second means we're allowing a maximum of 3 requests per 10 seconds.
  3. KeyGenerator determines how we identify a "user." Using c.IP() is a common and simple way to do this.
  4. LimitReached is a function that gets called when a user exceeds the limit. It's good practice to send a 429 Too Many Requests status code.
  5. If you run this and try to access /api/data more than 3 times in 10 seconds, you'll get our friendly "slow down" message.

3. Request Compression: Gzip and Deflate 📦

The Problem: You're sending large JSON responses or HTML pages to your users. The bigger the data, the longer it takes to travel over the network, especially for users on slower connections. It's like trying to mail a giant, fluffy pillow—you have to use a huge box, and it's cumbersome.

The Solution: Compression. Compression algorithms like Gzip and Deflate can shrink the size of your responses before sending them. This makes them travel faster over the network. It's like vacuum-sealing that pillow into a small, dense package before mailing it.

Fiber has a Compress middleware to handle this for you.

Getting Started with Compression

Let's install it.

bash
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/fiber/v2/middleware/compress

Hands-On Example

go
package main

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/compress"
)

func main() {
	app := fiber.New()

	// Use the compress middleware
	app.Use(compress.New(compress.Config{
		// You can set the compression level
		// LevelBestSpeed, LevelBestCompression, LevelDefault
		Level: compress.LevelBestSpeed,
	}))

	app.Get("/big-data", func(c *fiber.Ctx) error {
		// Imagine this is a very large JSON response
		return c.JSON(fiber.Map{
			"message": "This is a large amount of data that will be compressed!",
			// ... lots more data ...
		})
	})

	app.Listen(":3000")
}

What's happening here?

  1. We add the compress middleware.
  2. We can configure the Level of compression. LevelBestSpeed is a good balance, while LevelBestCompression will make the response smaller but use more CPU.
  3. That's it! The middleware is smart enough to check if the client supports compression (by looking at the Accept-Encoding header) and will compress the response if it does. You can verify this in your browser's developer tools under the "Network" tab. Look for the Content-Encoding: gzip header on the response.

4. Profiling Your Fiber Application 🧐

The Problem: Your application feels slow, but you don't know why. Is it a specific database query? A slow API call? A piece of code that's eating up CPU? Guessing is not a strategy! It's like trying to fix a car that's making a weird noise by randomly replacing parts.

The Solution: Profiling. Profiling is the process of analyzing your application's performance to identify bottlenecks. Go has excellent built-in tools for this, and we can easily integrate them with Fiber.

The pprof middleware is your best friend here.

Getting Started with Profiling

You'll need the pprof middleware from the contrib repository.

bash
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/pprof

Hands-On Example

go
package main

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/contrib/pprof"
)

func main() {
	app := fiber.New()

	// Use the pprof middleware
	// This will register the pprof routes at the default /debug/pprof
	app.Use(pprof.New())

	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("Hello, Profiler!")
	})

	// A sample route that might be slow
	app.Get("/slow", func(c *fiber.Ctx) error {
		// Simulate some heavy work
		sum := 0
		for i := 0; i < 1000000000; i++ {
			sum += i
		}
		return c.SendString("Done with heavy work!")
	})


	app.Listen(":3000")
}

How to Use It:

  1. Run your application.

  2. The profiler is now available at /debug/pprof/. For example, you can open http://localhost:3000/debug/pprof/ in your browser to see an overview.

  3. To get a CPU profile, you can use the go tool pprof command. While your app is running (and perhaps under some load, e.g., by visiting the /slow endpoint a few times), run this in your terminal:

    bash
    go tool pprof http://localhost:3000/debug/pprof/profile?seconds=10
  4. This will collect CPU data for 10 seconds and then open an interactive prompt. Type top to see the functions that are using the most CPU. Type web to generate a cool visual graph (you might need to install Graphviz for this).

This powerful tool helps you pinpoint exactly where your application is spending its time, so you can optimize intelligently. No more guesswork!


Further Reading & References 📚

Challenge

Challenge: Optimize a Fiber API Endpoint

Your task is to build a high-performance Fiber API endpoint by integrating several optimization middleware. You will create a single endpoint /data that is protected by a rate limiter, serves compressed responses, and caches results to avoid redundant processing.

Requirements:

  1. Initialize a new Fiber application.
  2. Create a GET endpoint at /data.
  3. Inside the /data handler, simulate a slow operation by pausing execution for 2 seconds (time.Sleep).
  4. The handler should return a JSON object containing at least five key-value pairs. One of the keys should be timestamp with the current time.
  5. Compression: Apply the Compress middleware to the application. Configure it to use the LevelBestSpeed for compression.
  6. Rate Limiting: Apply the Limiter middleware. Configure it to allow a maximum of 5 requests per minute from a single client (identified by IP address).
  7. Caching: Apply the Cache middleware to the /data endpoint. Configure it so that responses are cached for 30 seconds.
  8. Finally, start the Fiber application to listen on port 3000.

Expected result

Your final code should be a complete, runnable Go program that sets up a Fiber web server with the three specified middleware (Compress, Limiter, Cache) configured according to the requirements.

A correct solution must contain:

  • An initialized Fiber app: app := fiber.New()
  • The compress.New() middleware configured with Level: compress.LevelBestSpeed.
  • The limiter.New() middleware configured with Max: 5 and Expiration: 1 * time.Minute.
  • The cache.New() middleware configured with Expiration: 30 * time.Second.
  • A GET route for /data (app.Get("/data", ...)).
  • The route handler function must include time.Sleep(2 * time.Second) before returning a JSON response.
  • The response should be a valid JSON object created using c.JSON(...).
  • The server must be started using app.Listen(":3000").
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.