SlideShare a Scribd company logo
1 of 66
Building Scalable,
Distributed Job Queues
    with Redis and
  Redis::Client
       Mike Friedman
          (friedo)

      YAPC NA 2012
What Redis is


• Open-source
• Key-value store
• Simple
• Fast
What Redis isn’t

• Relational (e.g. MySQL, Postgres, Oracle)
• Document store (e.g. MongoDB)
• Structured (e.g. Cassandra)
• HTTP
Redis Data Types

• Strings
 • e.g. ‘foo’, ’42’, or a JSON blob
 • Think Perl scalars
Redis Data Types

• Lists
 • Zero or more strings, ordered
 • RPUSH, RPOP, LPUSH, and LPOP ==
   push, pop, unshift, and shift in
   Perl
Redis Data Types

• Hashes
 • Zero or more key-value pairs, unordered
   • HDEL, HEXISTS, HKEYS, and HVALS
      == delete, exists, keys, and
      values in Perl
Redis Data Types


• Some types are not directly analogous to
  Perl concepts
Redis Data Types

• Sets
 • Zero or more keys, unordered
 • No values
 • Think of a Perl hash where all values are
    undef
Redis Data Types


• Sets
 • SREM, SISMEMBER, SMEMBERS ==
   delete, exists, and keys in Perl
Redis Data Types

• Set operations
 • Union
 • Intersection
 • Add / remove
 • Cardinality
Redis Data Types


• Set operations can be implemented with
  Perl hashes
• How?
Redis Data Types
• Sorted Sets (zsets)
 • Zero or more keys, each with a numeric
    “score”
 • No values
 • Can be modeled as a Perl hash where the
    values are the scores
Redis Data Types


• Sorted Sets (zsets)
 • ZREM, ZRANK, and ZRANGE (loosely)
   == delete, exists, and keys in Perl
Redis Data Types

• Sorted set operations
 • Cardinality (within ranges)
 • Union / intersection
 • Lots more
Redis Data Types


• Many more commands for working with
  Redis types
• See http://redis.io/commands for the full list
Redis Protocol


• Not HTTP
• Stateful, interactive protocol
Redis Protocol


• Actually, there are TWO protocols
Redis Protocol

• Old Protocol
• Client commands sent one per line
• Server responses sent immediately
Redis Protocol
• Old Protocol example:
  SET mystring foobar
  +OK
Redis Protocol
• Old Protocol problems:
 • Command and data separated with
    whitespace
 • Difficult to parse - escaping becomes an
    issue
 • Difficult to deal with binary data or
    encoded text
 • Inconsistent
Redis Protocol


• New Protocol (Unified Request Protocol)
 • Also called the URP
Redis Protocol
• URP
 • Consistent command syntax
 • All data are prefixed with a byte length
 • No escaping or encoding/decoding
    required
 • Binary round-trip safe
Redis Protocol
• URP Example
  *3
  $3
  SET
  $8
  mystring
  $6
  foobar
  +OK
Redis Protocol
• URP Example
  *3
  $3
  SET
  $8
  mystring
  $6
  foobar
  +OK
Redis Protocol
• URP Example
  *3
  $3
  SET
  $8
  mystring
  $6
  foobar
  +OK
Redis Protocol
• URP Example
  *3
  $3
  SET
  $8
  mystring
  $6
  foobar
  +OK
Redis Protocol
• URP Example
  *3
  $3
  SET
  $8
  mystring
  $6
  foobar
  +OK
Redis Dists on CPAN
Redis Dists on CPAN


• Information as of when I began work on
  Redis::Client, so some of this may have
  changed by now.
Redis Dists on CPAN
• Redis.pm
 • Simple interface; works
 • Does some odd things with encoding
 • No newer Redis types like hashes
 • AUTOLOAD :(
Redis Dists on CPAN

• Redis.pm
 • Forces UTF-8 flag on returned data by
    default
 • This is horribly broken
 • It will be fixed
Redis Dists on CPAN
• Redis::hiredis
 • Wrapper around hiredis binary client
 • Works well if you have hiredis
    available
 • External binary dependency
 • Slow IPC
Redis Dists on CPAN

• There was no Perl Redis module with:
 • Native support for Redis hashes
 • No outside binary dependencies
 • Full URP Support
Redis Dists on CPAN


 Until now!
Redis Dists on CPAN


     (Applause)
Redis Dists on CPAN


 (Applause)
Redis::Client


• On CPAN
 • https://metacpan.org/release/Redis-Client
Redis::Client


• On Github
 • https://github.com/friedo/perl-redis-client
Redis::Client

• Distribution structure
 • Redis/Client.pm
   • Primary interface, implements the
      Redis commands
Redis::Client
• Distribution structure
 • Redis/Client/Role/URP.pm
   • Moose role; implements the Unified
      Request Protocol
   • Abstract enough to be used by other
      projects
Redis::Client

• Distribution structure
 • Redis/Client/Role/Tied.pm
   • Moose role; common functionality for
      classes which map Redis types to Perl
      objects
Redis::Client

• Distribution structure
 • Redis/Client/*.pm
   • Tied object classes for Redis strings,
      lists, hashes, sets, and sorted sets
Redis::Client
• Distribution structure
 • Redis/Client/String.pm
 • Redis/Client/List.pm
 • Redis/Client/Hash.pm
 • Redis/Client/Set.pm
 • Redis/Client/Zset.pm
Redis::Client
• Encoding Caveats
 • Redis::Client makes no assumptions
    about your data encoding
 • Character data MUST be encoded prior
    to being sent to Redis
 • Redis URP relies on accurate BYTE
    counts, NOT character counts
 • Data returned from Redis NOT decoded
Redis::Client

• Future features
 • Callback registration system for
   • Encoding and decoding
   • Inflating and deflating
Redis::Client Examples

my $redis = Redis::Client->new;

# store a string
$redis->set( mystring => ‘foo’ );

# retrieve string
my $str = $redis->get(‘mystring’);
Redis::Client Examples

# work with lists
$redis->lpush(
   ‘mylist’, ‘one’, ‘two’, ‘three’
);

my $tail = $redis->rpop(‘mylist’);
# three
Redis::Client Examples
# work with hashes
$redis->hset(
   ‘myhash’, key => 42
);

my $val = $redis->hget(
   ‘myhash’, ‘key’
);
# 42
Redis::Client Examples
# work with tied classes
tie my %hash, ‘Redis::Client::Hash’,
  key => ‘myhash’, client => $redis;

my @keys = keys %hash;
if ( exists $hash{foo} ) { ... }
delete $hash{some_key};
while ( my ( $k, $v ) = each %hash )
  { ... }

# etc.
Job Queues
• Goals
 • Add jobs with arbitrary data to queue
 • Fetch and execute jobs as soon as
    possible
 • Prevent duplicate job execution
 • Thousands of jobs per hour
Job Queues
• Old Model
 • Jobs table in relational DB
 • INSERT to add job
 • Poll DB to find new jobs
 • Set a status field when job is running
 • Transactions to prevent duplicates
 • Set status to ‘done’ or ‘error’ for
    historical data
Job Queues

• Problems:
 • Relational DB is slow
 • Jobs table grows quickly; not scalable
 • Wrong tool for the job
Job Queues
• Using Redis:
 • A single Redis list implements a queue
 • LPOP (shift) jobs off the front of the
    queue
 • RPUSH (push) jobs onto the end of the
    queue
 • Use JSON to store job arguments and
    metadata
Job Queues

• Redis blocking push/pop
 • LPOP returns undef if no jobs
 • BLPOP command blocks until an item to
    shift exists
 • No need to poll server; just wait
Job Queues
# Simple Example of Job / Dispatcher

use   Redis::Client;
use   JSON::XS;
use   Module::Load;
use   TryCatch;

my $redis = Redis::Client->new;
Job Queues
# Add a job

my $job =
  { class => ‘Some::Job’,
    method => ‘do_something’,
    constructor_args => { foo => 42 },
    method_args => { bar => 43 } };

$redis->lpush( jobs => encode_json $job );
Job Queues
# Simple dispatcher loop

my $job_str = $redis->blpop(‘jobs’);
my $job = decode_json $job_str;
my %c_args
  = %{ $job->{constructor_args} };
my $m_args
  = %{ $job->{method_args} };
my $class
  = ‘MyApp::’ . $job->{class};
my $meth = $job->{method};
Job Queues
load $class;

my $obj = $class->new( %c_args );
try {
    $obj->$meth( %m_args );
} catch ( $err ) {
    # store error data --> relational DB
};

# store success data --> relational DB
Benchmarks
• Disclaimer:
 • These are bad benchmarks
 • Dependent on highly system-specific
    architecture
 • Didn’t try very hard
 • Do your own evaluation
Benchmarks
• Old system (MySQL jobs table with polling,
  5,000,000 dummy jobs populated)

                            100
       1 Worker 10 Workers
                           Workers


       88 jobs/   710 jobs/   3892 jobs/
       minute      minute      minute
         avg.       avg.         avg.
Benchmarks
• New system (Redis queue, historical data
  only in MySQL, 5,000,000 dummy jobs
  populated

                            100
       1 Worker 10 Workers
                           Workers


       92 jobs/   1011 jobs/ 9222 jobs/
       minute      minute     minute
         avg.        avg.       avg.
Caveats

• These benchmarks are stupid
• Highly specific test; do your own tests
• Most job time is spent doing the job, not
  talking to the dispatcher
• But it works for my purposes
Thank You
Have fun with Redis
 and Redis::Client
    Mike Friedman

   friedo@friedo.com
Questions

More Related Content

What's hot

Redis And python at pycon_2011
Redis And python at pycon_2011Redis And python at pycon_2011
Redis And python at pycon_2011sunilar0ra
 
PostgreSQL and Redis - talk at pgcon 2013
PostgreSQL and Redis - talk at pgcon 2013PostgreSQL and Redis - talk at pgcon 2013
PostgreSQL and Redis - talk at pgcon 2013Andrew Dunstan
 
ETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk LoadingETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk Loadingalex_araujo
 
Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...
Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...
Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...DataStax Academy
 
{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4琛琳 饶
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparisonshsedghi
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture ForumChristopher Spring
 
DBD::Gofer 200809
DBD::Gofer 200809DBD::Gofer 200809
DBD::Gofer 200809Tim Bunce
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageSATOSHI TAGOMORI
 
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...DataStax Academy
 
Aaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with ZabbixAaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with ZabbixZabbix
 
Extend Redis with Modules
Extend Redis with ModulesExtend Redis with Modules
Extend Redis with ModulesItamar Haber
 
Chapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDBChapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDBMongoDB
 
Elasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveElasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveSematext Group, Inc.
 
Attack monitoring using ElasticSearch Logstash and Kibana
Attack monitoring using ElasticSearch Logstash and KibanaAttack monitoring using ElasticSearch Logstash and Kibana
Attack monitoring using ElasticSearch Logstash and KibanaPrajal Kulkarni
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Michael Renner
 
Habits of Effective Sqoop Users
Habits of Effective Sqoop UsersHabits of Effective Sqoop Users
Habits of Effective Sqoop UsersKathleen Ting
 
Cassandra Community Webinar: Back to Basics with CQL3
Cassandra Community Webinar: Back to Basics with CQL3Cassandra Community Webinar: Back to Basics with CQL3
Cassandra Community Webinar: Back to Basics with CQL3DataStax
 
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...InfluxData
 

What's hot (20)

Redis And python at pycon_2011
Redis And python at pycon_2011Redis And python at pycon_2011
Redis And python at pycon_2011
 
PostgreSQL and Redis - talk at pgcon 2013
PostgreSQL and Redis - talk at pgcon 2013PostgreSQL and Redis - talk at pgcon 2013
PostgreSQL and Redis - talk at pgcon 2013
 
ETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk LoadingETL With Cassandra Streaming Bulk Loading
ETL With Cassandra Streaming Bulk Loading
 
Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...
Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...
Cassandra Summit 2014: Reading Cassandra SSTables Directly for Offline Data A...
 
{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture Forum
 
DBD::Gofer 200809
DBD::Gofer 200809DBD::Gofer 200809
DBD::Gofer 200809
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby Usage
 
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
Cassandra Day SV 2014: Netflix’s Astyanax Java Client Driver for Apache Cassa...
 
Aaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with ZabbixAaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with Zabbix
 
Extend Redis with Modules
Extend Redis with ModulesExtend Redis with Modules
Extend Redis with Modules
 
Chapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDBChapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDB
 
Elasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep diveElasticsearch for Logs & Metrics - a deep dive
Elasticsearch for Logs & Metrics - a deep dive
 
Attack monitoring using ElasticSearch Logstash and Kibana
Attack monitoring using ElasticSearch Logstash and KibanaAttack monitoring using ElasticSearch Logstash and Kibana
Attack monitoring using ElasticSearch Logstash and Kibana
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
 
HiveServer2
HiveServer2HiveServer2
HiveServer2
 
Habits of Effective Sqoop Users
Habits of Effective Sqoop UsersHabits of Effective Sqoop Users
Habits of Effective Sqoop Users
 
Cassandra Community Webinar: Back to Basics with CQL3
Cassandra Community Webinar: Back to Basics with CQL3Cassandra Community Webinar: Back to Basics with CQL3
Cassandra Community Webinar: Back to Basics with CQL3
 
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
 

Viewers also liked

RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueGleicon Moraes
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Itamar Haber
 
Delaying Gratification: Using queues to build efficient systems
Delaying Gratification: Using queues to build efficient systemsDelaying Gratification: Using queues to build efficient systems
Delaying Gratification: Using queues to build efficient systems10n Software, LLC
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
High-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using RedisHigh-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using Rediscacois
 
Scalable Streaming Data Pipelines with Redis
Scalable Streaming Data Pipelines with RedisScalable Streaming Data Pipelines with Redis
Scalable Streaming Data Pipelines with RedisAvram Lyon
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to CeleryIdan Gazit
 
Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...
Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...
Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...DataWorks Summit/Hadoop Summit
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Sylvain Zimmer
 
Distributed System Management
Distributed System ManagementDistributed System Management
Distributed System ManagementIbrahim Amer
 

Viewers also liked (11)

RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
 
Delaying Gratification: Using queues to build efficient systems
Delaying Gratification: Using queues to build efficient systemsDelaying Gratification: Using queues to build efficient systems
Delaying Gratification: Using queues to build efficient systems
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
High-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using RedisHigh-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using Redis
 
Scalable Streaming Data Pipelines with Redis
Scalable Streaming Data Pipelines with RedisScalable Streaming Data Pipelines with Redis
Scalable Streaming Data Pipelines with Redis
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...
Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...
Building Large-Scale Stream Infrastructures Across Multiple Data Centers with...
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
 
Distributed System Management
Distributed System ManagementDistributed System Management
Distributed System Management
 
Level DB - Quick Cheat Sheet
Level DB - Quick Cheat SheetLevel DB - Quick Cheat Sheet
Level DB - Quick Cheat Sheet
 

Similar to Building Scalable, Distributed Job Queues with Redis and Redis::Client

HIgh Performance Redis- Tague Griffith, GoPro
HIgh Performance Redis- Tague Griffith, GoProHIgh Performance Redis- Tague Griffith, GoPro
HIgh Performance Redis- Tague Griffith, GoProRedis Labs
 
Using Spring with NoSQL databases (SpringOne China 2012)
Using Spring with NoSQL databases (SpringOne China 2012)Using Spring with NoSQL databases (SpringOne China 2012)
Using Spring with NoSQL databases (SpringOne China 2012)Chris Richardson
 
Scaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLScaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLRichard Schneeman
 
10 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 201910 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 2019Dave Nielsen
 
10 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 201910 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 2019Dave Nielsen
 
Relational to Graph - Import
Relational to Graph - ImportRelational to Graph - Import
Relational to Graph - ImportNeo4j
 
Redis - The Universal NoSQL Tool
Redis - The Universal NoSQL ToolRedis - The Universal NoSQL Tool
Redis - The Universal NoSQL ToolEberhard Wolff
 
Big Data Developers Moscow Meetup 1 - sql on hadoop
Big Data Developers Moscow Meetup 1  - sql on hadoopBig Data Developers Moscow Meetup 1  - sql on hadoop
Big Data Developers Moscow Meetup 1 - sql on hadoopbddmoscow
 
Developing polyglot persistence applications #javaone 2012
Developing polyglot persistence applications  #javaone 2012Developing polyglot persistence applications  #javaone 2012
Developing polyglot persistence applications #javaone 2012Chris Richardson
 
Non-Relational Databases at ACCU2011
Non-Relational Databases at ACCU2011Non-Relational Databases at ACCU2011
Non-Relational Databases at ACCU2011Gavin Heavyside
 
Prometheus lightning talk (Devops Dublin March 2015)
Prometheus lightning talk (Devops Dublin March 2015)Prometheus lightning talk (Devops Dublin March 2015)
Prometheus lightning talk (Devops Dublin March 2015)Brian Brazil
 
Redis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRicard Clau
 
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...Thibaud Desodt
 
Developing polyglot persistence applications (SpringOne India 2012)
Developing polyglot persistence applications (SpringOne India 2012)Developing polyglot persistence applications (SpringOne India 2012)
Developing polyglot persistence applications (SpringOne India 2012)Chris Richardson
 
Redis everywhere - PHP London
Redis everywhere - PHP LondonRedis everywhere - PHP London
Redis everywhere - PHP LondonRicard Clau
 
Redis. Performance on custom searches. Production screw up
Redis. Performance on custom searches. Production screw upRedis. Performance on custom searches. Production screw up
Redis. Performance on custom searches. Production screw upPiotrWasiak5
 

Similar to Building Scalable, Distributed Job Queues with Redis and Redis::Client (20)

KeyValue Stores
KeyValue StoresKeyValue Stores
KeyValue Stores
 
HIgh Performance Redis- Tague Griffith, GoPro
HIgh Performance Redis- Tague Griffith, GoProHIgh Performance Redis- Tague Griffith, GoPro
HIgh Performance Redis- Tague Griffith, GoPro
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
Using Spring with NoSQL databases (SpringOne China 2012)
Using Spring with NoSQL databases (SpringOne China 2012)Using Spring with NoSQL databases (SpringOne China 2012)
Using Spring with NoSQL databases (SpringOne China 2012)
 
Scaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLScaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQL
 
10 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 201910 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 2019
 
10 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 201910 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 2019
 
Relational to Graph - Import
Relational to Graph - ImportRelational to Graph - Import
Relational to Graph - Import
 
Redis - The Universal NoSQL Tool
Redis - The Universal NoSQL ToolRedis - The Universal NoSQL Tool
Redis - The Universal NoSQL Tool
 
Big Data Developers Moscow Meetup 1 - sql on hadoop
Big Data Developers Moscow Meetup 1  - sql on hadoopBig Data Developers Moscow Meetup 1  - sql on hadoop
Big Data Developers Moscow Meetup 1 - sql on hadoop
 
Wmware NoSQL
Wmware NoSQLWmware NoSQL
Wmware NoSQL
 
Developing polyglot persistence applications #javaone 2012
Developing polyglot persistence applications  #javaone 2012Developing polyglot persistence applications  #javaone 2012
Developing polyglot persistence applications #javaone 2012
 
REDIS327
REDIS327REDIS327
REDIS327
 
Non-Relational Databases at ACCU2011
Non-Relational Databases at ACCU2011Non-Relational Databases at ACCU2011
Non-Relational Databases at ACCU2011
 
Prometheus lightning talk (Devops Dublin March 2015)
Prometheus lightning talk (Devops Dublin March 2015)Prometheus lightning talk (Devops Dublin March 2015)
Prometheus lightning talk (Devops Dublin March 2015)
 
Redis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHP
 
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
 
Developing polyglot persistence applications (SpringOne India 2012)
Developing polyglot persistence applications (SpringOne India 2012)Developing polyglot persistence applications (SpringOne India 2012)
Developing polyglot persistence applications (SpringOne India 2012)
 
Redis everywhere - PHP London
Redis everywhere - PHP LondonRedis everywhere - PHP London
Redis everywhere - PHP London
 
Redis. Performance on custom searches. Production screw up
Redis. Performance on custom searches. Production screw upRedis. Performance on custom searches. Production screw up
Redis. Performance on custom searches. Production screw up
 

More from Mike Friedman

Basic Symbolic Computation in Perl
Basic Symbolic Computation in PerlBasic Symbolic Computation in Perl
Basic Symbolic Computation in PerlMike Friedman
 
Make Your Own Perl with Moops
Make Your Own Perl with MoopsMake Your Own Perl with Moops
Make Your Own Perl with MoopsMike Friedman
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)Mike Friedman
 
21st Century CPAN Testing: CPANci
21st Century CPAN Testing: CPANci21st Century CPAN Testing: CPANci
21st Century CPAN Testing: CPANciMike Friedman
 
Data Modeling for the Real World
Data Modeling for the Real WorldData Modeling for the Real World
Data Modeling for the Real WorldMike Friedman
 
CPANci: Continuous Integration for CPAN
CPANci: Continuous Integration for CPANCPANci: Continuous Integration for CPAN
CPANci: Continuous Integration for CPANMike Friedman
 
MongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World ExamplesMongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World ExamplesMike Friedman
 
Building a MongoDB App with Perl
Building a MongoDB App with PerlBuilding a MongoDB App with Perl
Building a MongoDB App with PerlMike Friedman
 
Building Your First App with MongoDB
Building Your First App with MongoDBBuilding Your First App with MongoDB
Building Your First App with MongoDBMike Friedman
 

More from Mike Friedman (9)

Basic Symbolic Computation in Perl
Basic Symbolic Computation in PerlBasic Symbolic Computation in Perl
Basic Symbolic Computation in Perl
 
Make Your Own Perl with Moops
Make Your Own Perl with MoopsMake Your Own Perl with Moops
Make Your Own Perl with Moops
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)
 
21st Century CPAN Testing: CPANci
21st Century CPAN Testing: CPANci21st Century CPAN Testing: CPANci
21st Century CPAN Testing: CPANci
 
Data Modeling for the Real World
Data Modeling for the Real WorldData Modeling for the Real World
Data Modeling for the Real World
 
CPANci: Continuous Integration for CPAN
CPANci: Continuous Integration for CPANCPANci: Continuous Integration for CPAN
CPANci: Continuous Integration for CPAN
 
MongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World ExamplesMongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World Examples
 
Building a MongoDB App with Perl
Building a MongoDB App with PerlBuilding a MongoDB App with Perl
Building a MongoDB App with Perl
 
Building Your First App with MongoDB
Building Your First App with MongoDBBuilding Your First App with MongoDB
Building Your First App with MongoDB
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Building Scalable, Distributed Job Queues with Redis and Redis::Client

  • 1. Building Scalable, Distributed Job Queues with Redis and Redis::Client Mike Friedman (friedo) YAPC NA 2012
  • 2. What Redis is • Open-source • Key-value store • Simple • Fast
  • 3. What Redis isn’t • Relational (e.g. MySQL, Postgres, Oracle) • Document store (e.g. MongoDB) • Structured (e.g. Cassandra) • HTTP
  • 4. Redis Data Types • Strings • e.g. ‘foo’, ’42’, or a JSON blob • Think Perl scalars
  • 5. Redis Data Types • Lists • Zero or more strings, ordered • RPUSH, RPOP, LPUSH, and LPOP == push, pop, unshift, and shift in Perl
  • 6. Redis Data Types • Hashes • Zero or more key-value pairs, unordered • HDEL, HEXISTS, HKEYS, and HVALS == delete, exists, keys, and values in Perl
  • 7. Redis Data Types • Some types are not directly analogous to Perl concepts
  • 8. Redis Data Types • Sets • Zero or more keys, unordered • No values • Think of a Perl hash where all values are undef
  • 9. Redis Data Types • Sets • SREM, SISMEMBER, SMEMBERS == delete, exists, and keys in Perl
  • 10. Redis Data Types • Set operations • Union • Intersection • Add / remove • Cardinality
  • 11. Redis Data Types • Set operations can be implemented with Perl hashes • How?
  • 12. Redis Data Types • Sorted Sets (zsets) • Zero or more keys, each with a numeric “score” • No values • Can be modeled as a Perl hash where the values are the scores
  • 13. Redis Data Types • Sorted Sets (zsets) • ZREM, ZRANK, and ZRANGE (loosely) == delete, exists, and keys in Perl
  • 14. Redis Data Types • Sorted set operations • Cardinality (within ranges) • Union / intersection • Lots more
  • 15. Redis Data Types • Many more commands for working with Redis types • See http://redis.io/commands for the full list
  • 16. Redis Protocol • Not HTTP • Stateful, interactive protocol
  • 17. Redis Protocol • Actually, there are TWO protocols
  • 18. Redis Protocol • Old Protocol • Client commands sent one per line • Server responses sent immediately
  • 19. Redis Protocol • Old Protocol example: SET mystring foobar +OK
  • 20. Redis Protocol • Old Protocol problems: • Command and data separated with whitespace • Difficult to parse - escaping becomes an issue • Difficult to deal with binary data or encoded text • Inconsistent
  • 21. Redis Protocol • New Protocol (Unified Request Protocol) • Also called the URP
  • 22. Redis Protocol • URP • Consistent command syntax • All data are prefixed with a byte length • No escaping or encoding/decoding required • Binary round-trip safe
  • 23. Redis Protocol • URP Example *3 $3 SET $8 mystring $6 foobar +OK
  • 24. Redis Protocol • URP Example *3 $3 SET $8 mystring $6 foobar +OK
  • 25. Redis Protocol • URP Example *3 $3 SET $8 mystring $6 foobar +OK
  • 26. Redis Protocol • URP Example *3 $3 SET $8 mystring $6 foobar +OK
  • 27. Redis Protocol • URP Example *3 $3 SET $8 mystring $6 foobar +OK
  • 29. Redis Dists on CPAN • Information as of when I began work on Redis::Client, so some of this may have changed by now.
  • 30. Redis Dists on CPAN • Redis.pm • Simple interface; works • Does some odd things with encoding • No newer Redis types like hashes • AUTOLOAD :(
  • 31. Redis Dists on CPAN • Redis.pm • Forces UTF-8 flag on returned data by default • This is horribly broken • It will be fixed
  • 32. Redis Dists on CPAN • Redis::hiredis • Wrapper around hiredis binary client • Works well if you have hiredis available • External binary dependency • Slow IPC
  • 33. Redis Dists on CPAN • There was no Perl Redis module with: • Native support for Redis hashes • No outside binary dependencies • Full URP Support
  • 34. Redis Dists on CPAN Until now!
  • 35. Redis Dists on CPAN (Applause)
  • 36. Redis Dists on CPAN (Applause)
  • 37. Redis::Client • On CPAN • https://metacpan.org/release/Redis-Client
  • 38.
  • 39. Redis::Client • On Github • https://github.com/friedo/perl-redis-client
  • 40.
  • 41. Redis::Client • Distribution structure • Redis/Client.pm • Primary interface, implements the Redis commands
  • 42. Redis::Client • Distribution structure • Redis/Client/Role/URP.pm • Moose role; implements the Unified Request Protocol • Abstract enough to be used by other projects
  • 43. Redis::Client • Distribution structure • Redis/Client/Role/Tied.pm • Moose role; common functionality for classes which map Redis types to Perl objects
  • 44. Redis::Client • Distribution structure • Redis/Client/*.pm • Tied object classes for Redis strings, lists, hashes, sets, and sorted sets
  • 45. Redis::Client • Distribution structure • Redis/Client/String.pm • Redis/Client/List.pm • Redis/Client/Hash.pm • Redis/Client/Set.pm • Redis/Client/Zset.pm
  • 46. Redis::Client • Encoding Caveats • Redis::Client makes no assumptions about your data encoding • Character data MUST be encoded prior to being sent to Redis • Redis URP relies on accurate BYTE counts, NOT character counts • Data returned from Redis NOT decoded
  • 47. Redis::Client • Future features • Callback registration system for • Encoding and decoding • Inflating and deflating
  • 48. Redis::Client Examples my $redis = Redis::Client->new; # store a string $redis->set( mystring => ‘foo’ ); # retrieve string my $str = $redis->get(‘mystring’);
  • 49. Redis::Client Examples # work with lists $redis->lpush( ‘mylist’, ‘one’, ‘two’, ‘three’ ); my $tail = $redis->rpop(‘mylist’); # three
  • 50. Redis::Client Examples # work with hashes $redis->hset( ‘myhash’, key => 42 ); my $val = $redis->hget( ‘myhash’, ‘key’ ); # 42
  • 51. Redis::Client Examples # work with tied classes tie my %hash, ‘Redis::Client::Hash’, key => ‘myhash’, client => $redis; my @keys = keys %hash; if ( exists $hash{foo} ) { ... } delete $hash{some_key}; while ( my ( $k, $v ) = each %hash ) { ... } # etc.
  • 52. Job Queues • Goals • Add jobs with arbitrary data to queue • Fetch and execute jobs as soon as possible • Prevent duplicate job execution • Thousands of jobs per hour
  • 53. Job Queues • Old Model • Jobs table in relational DB • INSERT to add job • Poll DB to find new jobs • Set a status field when job is running • Transactions to prevent duplicates • Set status to ‘done’ or ‘error’ for historical data
  • 54. Job Queues • Problems: • Relational DB is slow • Jobs table grows quickly; not scalable • Wrong tool for the job
  • 55. Job Queues • Using Redis: • A single Redis list implements a queue • LPOP (shift) jobs off the front of the queue • RPUSH (push) jobs onto the end of the queue • Use JSON to store job arguments and metadata
  • 56. Job Queues • Redis blocking push/pop • LPOP returns undef if no jobs • BLPOP command blocks until an item to shift exists • No need to poll server; just wait
  • 57. Job Queues # Simple Example of Job / Dispatcher use Redis::Client; use JSON::XS; use Module::Load; use TryCatch; my $redis = Redis::Client->new;
  • 58. Job Queues # Add a job my $job = { class => ‘Some::Job’, method => ‘do_something’, constructor_args => { foo => 42 }, method_args => { bar => 43 } }; $redis->lpush( jobs => encode_json $job );
  • 59. Job Queues # Simple dispatcher loop my $job_str = $redis->blpop(‘jobs’); my $job = decode_json $job_str; my %c_args = %{ $job->{constructor_args} }; my $m_args = %{ $job->{method_args} }; my $class = ‘MyApp::’ . $job->{class}; my $meth = $job->{method};
  • 60. Job Queues load $class; my $obj = $class->new( %c_args ); try { $obj->$meth( %m_args ); } catch ( $err ) { # store error data --> relational DB }; # store success data --> relational DB
  • 61. Benchmarks • Disclaimer: • These are bad benchmarks • Dependent on highly system-specific architecture • Didn’t try very hard • Do your own evaluation
  • 62. Benchmarks • Old system (MySQL jobs table with polling, 5,000,000 dummy jobs populated) 100 1 Worker 10 Workers Workers 88 jobs/ 710 jobs/ 3892 jobs/ minute minute minute avg. avg. avg.
  • 63. Benchmarks • New system (Redis queue, historical data only in MySQL, 5,000,000 dummy jobs populated 100 1 Worker 10 Workers Workers 92 jobs/ 1011 jobs/ 9222 jobs/ minute minute minute avg. avg. avg.
  • 64. Caveats • These benchmarks are stupid • Highly specific test; do your own tests • Most job time is spent doing the job, not talking to the dispatcher • But it works for my purposes
  • 65. Thank You Have fun with Redis and Redis::Client Mike Friedman friedo@friedo.com

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n