Bun + Redis Guide
0 428
๐ Introduction to Bun + Redis
Pairing Bun, the ultra-fast JavaScript runtime, with Redis, the blazing in-memory key-value store, opens up a whole new world of performance-driven development.
Whether you're caching API responses, storing sessions, or building a real-time leaderboard, Redis is the tool, and Bun makes it lightning fast.
๐ Why Use Redis with Bun?
- โก High-speed caching: Redis operates entirely in memory, perfect for speeding up API responses.
- ๐ Data structures: Support for hashes, lists, sets, sorted sets, and more.
- ๐งต Pub/Sub support: Build chat apps, notifications, or real-time features with ease.
- ๐ฏ Session storage: Lightweight and fast storage for sessions or temporary auth tokens.
๐ฆ Installing Redis Client in Bun
Currently, the most Bun-compatible Redis client is ioredis
. Install it with:
bun add ioredis
Make sure Redis server is running locally or remotely. You can install Redis using your OS package manager (like brew install redis
on macOS).
๐ Connecting Bun to Redis
// redis.ts
import Redis from "ioredis";
const redis = new Redis(); // defaults to localhost:6379
export default redis;
This single file lets you import and use Redis anywhere in your Bun project.
๐ฅ Basic Redis Operations
Let's try some simple key-value operations in Redis using Bun.
// app.ts
import redis from './redis.ts';
await redis.set("greeting", "Hello from Bun + Redis!");
const value = await redis.get("greeting");
console.log("๐จ Redis says:", value); // Output: Hello from Bun + Redis!
These basic commands demonstrate how Redis stores and retrieves data asynchronously, even within Bunโs superfast runtime.
๐ง Using Redis Data Structures
Redis shines beyond simple key-value storage.
Here's how to use a few advanced structures:
// Lists
await redis.lpush("tasks", "build", "test", "deploy");
const tasks = await redis.lrange("tasks", 0, -1);
console.log("๐๏ธ Task list:", tasks);
// Hashes
await redis.hset("user:1", { name: "Aditya", age: "25" });
const user = await redis.hgetall("user:1");
console.log("๐ User details:", user);
// Sorted Sets
await redis.zadd("scores", 100, "Alice", 120, "Bob");
const leaderboard = await redis.zrevrange("scores", 0, -1, "WITHSCORES");
console.log("๐ Leaderboard:", leaderboard);
๐ก Using Redis Pub/Sub in Bun
Redis is often used for messaging or signaling between services.
Hereโs a simple example using Pub/Sub:
// publisher.ts
import redis from "./redis.ts";
setInterval(() => {
redis.publish("news", `๐ฐ Update at ${new Date().toISOString()}`);
}, 2000);
// subscriber.ts
import Redis from "ioredis";
const sub = new Redis();
sub.subscribe("news", () => {
console.log("๐ข Subscribed to news channel");
});
sub.on("message", (channel, message) => {
console.log(`๐ [${channel}]: ${message}`);
});
This allows you to build event-based systems or real-time feeds โ perfect for dashboards, games, and chat systems.
๐ก๏ธ Handling Errors Gracefully
Redis operations may fail due to network issues, expired keys, or incorrect formats.
Always wrap your logic:
try {
const data = await redis.get("maybe-missing-key");
console.log("๐งฉ Value:", data ?? "No data found");
} catch (err) {
console.error("โ Redis error:", err);
}
๐๏ธ Bun Server + Redis Cache Example
Letโs cache a computed response to improve performance in a simple Bun server:
// server.ts
import redis from './redis.ts';
Bun.serve({
port: 3000,
fetch: async (req) => {
let data = await redis.get("cached-response");
if (!data) {
console.log("โณ Cache miss. Calculating...");
data = JSON.stringify({ message: "Hello from Bun with Redis Cache!" });
await redis.set("cached-response", data, "EX", 10); // 10 sec expiry
} else {
console.log("โ
Cache hit!");
}
return new Response(data, {
headers: { "Content-Type": "application/json" },
});
},
});
This small cache layer can drastically reduce processing time for repeated calls.
๐งพ Final Thoughts
The combination of Bun + Redis is a developerโs dream for speed, simplicity, and power. From basic caching to real-time communication, Redis complements Bunโs performance-driven nature perfectly.
If you're building APIs, real-time apps, dashboards, or games โ or just need a quick and fast cache โ Redis and Bun will take you far. ๐ฅ
Try it out, build something fast, and keep caching smart. ๐
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments