• Stars
    star
    154
  • Rank 242,095 (Top 5 %)
  • Language
    JavaScript
  • Created over 12 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

High-availability redis in Node.js.

haredis

High-availability redis in Node.js

build status

(note: Travis-CI support for this project is a work in progress. If the build badge is red above, it's likely not really a problem with haredis, but rather a problem with Travis-CI running my tests. Tests pass locally for me!)

Idea

haredis is a code wrapper around node_redis which adds fault-taulerance to your application.

Features:

  • Drop-in replacement for node_redis
  • Easily build a cluster out of 3 or more (default-configured) redis servers
  • Auto-failover due to connection drops
  • Master conflict resolution (default your servers to master, and haredis will elect the freshest and issue the SLAVEOF commands)
  • Freshness judged by an opcounter (incremented on write)
  • Locking mechanism to prevent failover contention
  • Load-balancing for reads and pub/sub
  • One-client pub/sub
  • Gossip channel for quick failover

Usage

Start up multiple redis daemons, with no special configuration necessary, and list them like so:

var redis = require('haredis')
  , nodes = ['1.2.3.1:6379', '1.2.3.2:6379', '1.2.3.3:6379']
  , client = redis.createClient(nodes)
  ;

...then use client as you would use node_redis. If the master node goes down, haredis will automatically determine which node to promote to master, and keep standby connections to the others.

If multiple haredis clients are connected, a locking mechanism is implemented to prevent contention between failover attempts.

To see this in action,

  • Set up 3 local redis daemons on ports 6380-82
  • 6380 should be SLAVEOF NO ONE. 6381 and 82 should be slaves to 6380.
  • Run test/basic.js or test/pubsub.js (try multiple to test contention)
  • Kill the process listening on 6380 (master). haredis will auto-failover to the node it detects is freshest, set that to master, and the others to slaves!
  • Bring up 6380, and it will be added as standby for failover.

API differences

createClient

In haredis, createClient works like this:

function createClient([host/port array], options)

The first argument can be an array of hosts (using default port), ports (using localhost), or colon-separated strings (i.e., 1.2.3.4:6379). haredis will attempt to connect to all of these servers.

options corresponds to the same options you would pass node_redis. haredis additionally supports:

  • haredis_db_num {Number} database number that haredis should store metadata in (such as an opcounter). Defaults to 15.

auth

auth works like this:

function auth({host/port to password object}, callback)

The first argument can be an object of hosts, ports mapped to passwords (i.e., {'1.2.3.1:6379': 'pass1', '1.2.3.3:6379': 'pass2'}), or just the password string.

Load-balancing

haredis can optionally load-balance read operations to random slaves. Pub/sub subscriptions will automatically try to use a slave. For normal read-only commands, you can choose to query a random slave by using the slaveOk() method:

client.slaveOk().GET('foo', function(err, reply) { ...

slaveOk() will only affect the current command.

To load-balance all reads, you can set options.auto_slaveok = true in createClient(). Be advised that this can case problems due to replication delay!

To force a read to go to master when using auto_slaveok, use slaveOk(false) before the command:

client.slaveOk(false).GET('foo', function(err, reply) { ...

One-client pub/sub

In redis, pub/sub is a "mode" which excludes the use of regular commands while subscriptions are active. Normally you need to make separate client objects to use publish on one and subscribe on the other.

haredis adds the nice ability to use pub/sub simultaneously with regular commands. This is because it keeps internal redis clients in pub/sub mode for internal "gossip", but also makes it available for users. Of course this is optional, and you can always maintain a separate haredis client for subscribes if you wish.

Advice

For proper failover, a majority of the nodes need to be still online. This means that the minimum number of nodes should be 3. Under the minimum setup, you can lose up to 1 node. If only 1/3 are up, commands will be queued indefinitely until another node comes up.

Debugging/verbose logging

To see what's under the hood, try setting redis.debug_mode = true, and you can see the failover process in detail:

[19:27:58](#1) warning: MASTER is down! (127.0.0.1:6380)
[19:27:58](#1) info: reorientating (node down) in 2000ms
Redis connection gone from end event.
[19:28:00](#1) info: orientating (node down, 2/3 nodes up) ...
[19:28:00](#1) warning: invalid master count: 0
[19:28:00](#1) info: attempting failover!
[19:28:00](#1) info: my failover id: gP0SCM1B
[19:28:00](#1) info: lock was a success!
[19:28:00](#1) info: 127.0.0.1:6381 had highest opcounter (1441) of 2 nodes. congrats!
[19:28:00](#1) info: making 127.0.0.1:6382 into a slave...
[19:28:00](#1) info: 127.0.0.1:6382 is slave
[19:28:00](#1) info: publishing gossip:master for 127.0.0.1:6381
[19:28:00](#1) info: renegotating subSlave away from master
[19:28:00](#1) info: subSlave is now 127.0.0.1:6382
[19:28:00](#1) info: ready, using 127.0.0.1:6381 as master

To get info on which commands are executed on which servers, try setting redis.command_logging = true.

Running tests

haredis includes the test suite from node_redis which can be run in single or clustered mode.

If you have redis daemons running locally on ports 6380, 6381 and 8382, you can run the clustered test with:

$ make test-cluster

Or in single-mode with a redis server on port 6379:

$ make test

LICENSE - "MIT License"

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

bot18

Bot18 is a high-frequency cryptocurrency trading bot developed by Zenbot creator @carlos8f
HTML
193
star
2

buffet

Performance-oriented static file server
JavaScript
190
star
3

node-relations

Entity relationship, role, and permissions API for Node.js
JavaScript
61
star
4

node-upstarter

Easily create upstart services for your node apps
JavaScript
48
star
5

zenbrain

A framework for machine-learning bots
CSS
47
star
6

bundle-deps

easy command to bundle all your node.js dependencies
JavaScript
38
star
7

salty

Alternative public key encryption using NaCl
JavaScript
27
star
8

node-idgen

Minimal ID generator
JavaScript
25
star
9

node-middler

An embeddable middleware runner
JavaScript
22
star
10

node-cli-prompt

A tiny CLI prompter
JavaScript
20
star
11

node-coremidi

Allow Node.js to interact with CoreMIDI services on Mac OS platforms
C++
17
star
12

node-midi-api

An API to simplify MIDI message generation
JavaScript
15
star
13

hydration

Type-accurate serialization of javascript objects
JavaScript
15
star
14

modeler

simple entity system using a functional approach
JavaScript
13
star
15

searching-for-satoshi

i'm looking. where are you?
10
star
16

node-hashcashgen

Simple module implementing the hashcash algorithm
JavaScript
10
star
17

slam

Pure node benchmarker alternative to ab or siege
JavaScript
10
star
18

pemtools

Convert Buffers to/from PEM strings, and read/write SSH/RSA key files. Supports DEK encryption. (Node.js)
JavaScript
8
star
19

saw

actually working file tree watching library
JavaScript
8
star
20

cmmc

Mirror of David Cope's software from Computer Models of Musical Creativity
Common Lisp
8
star
21

node-timebucket

Group timestamps into "buckets" by applying a granularity to a discrete value
JavaScript
7
star
22

engine.oil

Makes running with engine.io a little slicker
JavaScript
7
star
23

that.js

Advanced Node.js framework featuring Evented Evolution Engine, Seamless State Sharing, and Plugin-optimized Operation
JavaScript
6
star
24

s8f.org

My personal website
HTML
5
star
25

node-benchmarx

HTTP-based side-by-side benchmark framework
JavaScript
5
star
26

zenbot_gdax

Zenbot supporting code for GDAX
JavaScript
5
star
27

node-dish

Miniature in-memory http static middleware optimized for serving buffers or strings
JavaScript
5
star
28

gfm-linkify

linkify repository references in github-flavored markdown text, such as sha1, user/repo@sha1, #issue, etc
4
star
29

node-accesslog

Simple common/combined access log middleware
JavaScript
4
star
30

node-tweetbot

Your own markov-chain-based twitter buddy.
JavaScript
4
star
31

ccl-play-soft-midi

Port of Apple PlaySoftMIDI example to Clozure Common Lisp
Common Lisp
4
star
32

motley

highly pluggable, agile http site development framework (Node.js)
JavaScript
4
star
33

lsmidi

Simple command to list midi devices available
JavaScript
3
star
34

metageo

A simple geographic data server using PHP, MongoDB and the GeoJSON spec.
PHP
3
star
35

bladerunner

request router for HTTP or complex async tasks
JavaScript
3
star
36

login-with-github

middleware making it easy to use github as authentication
JavaScript
3
star
37

modeler-redis

redis-powered functional entity system
JavaScript
3
star
38

micro-request

zero-depdency http(s) client
JavaScript
3
star
39

node-addr

Get the remote address of a request, with reverse-proxy support
JavaScript
2
star
40

codeid

A dead simple, random 8-character, universal \"New Unique ID\" string generator, using uppercase letters and numbers that don't look alike. A.K.A., UUIDs FOR HUMANS.
JavaScript
2
star
41

likejagger

2
star
42

dgate

Domain gateway, a simple clustered HTTP virtual host router
JavaScript
2
star
43

arena5

Fork of http://www.kevs3d.co.uk/dev/arena5/
JavaScript
2
star
44

node-tinyauth

Really basic basic authentication middleware
JavaScript
2
star
45

ssh-keygen2

Automate the ssh-keygen command for generating RSA keypairs
JavaScript
2
star
46

node-prog

Prints the source code of a program. Nice screen saver!
JavaScript
1
star
47

socketbench

Benchmarks for web sockets.
JavaScript
1
star
48

salty-gui

web GUI for Salty pubkey crypto
JavaScript
1
star
49

HaikuFox

A Haiku/BeOS style firefox theme originally by Doug Shelton.
1
star
50

sosa_redis

Simple Object Storage Abstraction, redis version
JavaScript
1
star
51

webgram

A web UI for exploring Instagram photos.
JavaScript
1
star
52

world.js

JavaScript
1
star
53

cryptic

easy two-way encryption
JavaScript
1
star
54

sosa_mongo

Simple Object Storage Abstraction, mongo version
JavaScript
1
star
55

socket-game

Multiplayer game demo using sockets.
JavaScript
1
star
56

node-conflation

Helps aggregate subject-predicate-object triples into condensed "digests"
JavaScript
1
star
57

zeropoint

Multiplayer space game.
JavaScript
1
star
58

ytunes

download and convert YouTube videos to mp3
JavaScript
1
star
59

href

middleware providing the current absolute url as req.href
JavaScript
1
star
60

keylogger

capture input from stdin transparently
JavaScript
1
star
61

foilmethod

Band website for FOIL Method.
JavaScript
1
star
62

int-packer

Pack integers into bigger integers
JavaScript
1
star
63

demondays

Plays "Demon Days" by the Gorillaz.
JavaScript
1
star
64

spacemantis

Space multiplayer game in 2.5D.
JavaScript
1
star
65

node-midi-stream

Stream interface for MIDI messages
JavaScript
1
star
66

carlos8f.github.com

JavaScript
1
star
67

idle-miner

Mine bitcoins automatically while your machine is idle
Shell
1
star
68

redis_failover

A Redis automatic failover mechanism
JavaScript
1
star
69

js-test

JavaScript
1
star
70

mus.txt

Text-based music notation using solfeggio
1
star
71

score.js

Text-based musical scoring parser for Node.js
JavaScript
1
star
72

sess

connect/express-style session middleware for apps that don't use connect/express
JavaScript
1
star
73

gistpress

A blog engine built around around gists and github users
JavaScript
1
star
74

node-namegen

Generate random names
JavaScript
1
star
75

modeler-leveldb

leveldb-powered functional entity system
JavaScript
1
star
76

mtgox-orderbook-recorder

Records Mt.Gox order book stream to a CSV file
JavaScript
1
star
77

pempal

Read and write PEM strings, optionally with encryption
JavaScript
1
star
78

node-chat-yardstick

Test scalability of simple chat program using various socket backends
JavaScript
1
star
79

extra

parse extra arguments to a command after "--"
JavaScript
1
star
80

mtgox-synth

Music generation driven by bitcoin trading at Mt.Gox
JavaScript
1
star
81

passport-freedomworks

FreedomWorks authentication strategy for Passport.
JavaScript
1
star
82

mac-synth

Unleash the internal General MIDI synth of your mac
C++
1
star
83

json-stable-stringify

deterministic JSON.stringify() with custom sorting to get deterministic hashes from stringified results
JavaScript
1
star
84

node-mefirst

Attach an event listener to run first.
JavaScript
1
star
85

botmaker

A dead simple way to make your own Twitter bots.
1
star