Couchbase::Client - Perl Couchbase Client

This module is no longer maintained. Use the Couchbase module instead

This is for the OLDER client library. The new library is simply called Couchbase.


This page documents the API of Couchbase::Client. To install this module, see Couchbase::Client::README for a broader overview.

See that same page for a list of current known issues as well.


    use Couchbase::Client;
    use Couchbase::Client::Errors;

    my $client = Couchbase::Client->new({
        server => 'localhost:8091',
        username => 'some_user',
        password => 'secret',
        bucket => 'my_bucket'

Possible connection errors:

    foreach my $err (@{$client->get_errors}) {
        my ($errnum,$errstr) = @$err;
        warn("Trouble ahead! Couchbase client says: $errstr.");
    my $opret;

Simple get and set:

    $opret = $client->set(Hello => "World", 3600);
    if(!$opret->is_ok) {
        warn("Couldn't set 'Hello': ". $opret->errstr);

    $opret = $client->get("Hello");
    if($opret->value) {
        printf("Got %s for 'Hello'\n", $opret->value);
    } else {
        warn("Couldn't get value for 'Hello': ". $opret->errstr);

Update expiration:

    #make 'Hello' entry expire in 120 seconds
    $client->touch("Hello", 120);

Atomic CAS

    $opret = $client->get("Hello");
    if($opret->value && $opret->value != "Planet") {
        $opret = $client->cas(Hello => 'Planet', $opret->cas);

        #check if atomic set was OK:
        if(!$opret->is_ok) {
            warn("Couldn't update: ".$opret->errstr);


<Couchbase::Client> is the client for couchbase (, which is based partially on the memcached server and the Memcache protocol.

In further stages, this module will attempt to retain backwards compatibility with older memcached clients like Cache::Memcached and Cache::Memcached::Fast

This client is mainly written in C and interacts with libcouchbase - the common couchbase client library, which must be installed.


All of the protocol methods ("get", "set", etc) return a common return value of Couchbase::Client::Return which stores operation-specific information and common status.

For simpler versions of return values, see Couchbase::Client::Compat which tries to support the Cache::Memcached::* interface.


Create a new object. Takes a hashref of options. The following options are currently supported

Typical Constructor Options


The host and port of the couchbase server to connect to. If ommited, defaults to localhost:8091.


A list of servers to try, in order. Couchbase::Client will connect to the first responsive server (optionally complaining with warnings about failed servers).

This is a special construction-time option. It will not work in conjunction with the "no_init_connect" option.

By virtue of the design of the Couchbase architecture, already-connected clients will learn about alternate entry points once an initial entry into the cluster has been established. Therefore if a connection fails in-situ, the client is likely to know of alternate entry points, and thus the server list is only useful for discovering the initial entry point.

username, password

Authentication credentials for the connection. Defaults to NULL


The bucket name for the connection. Defaults to default


These all alias to the same setting, and control the time the client waits for a response after it sends a request to the server.

The value should be specified in seconds (fractional values are allowed)

Defaults to 2.5

Conversion Options

The following options for conversion can be specified. Some of the compression code is borrowed from Cache::Memcached::Fast, with some modifications.

First, a note about compression and conversion:

Compression and conversion as done by legacy memcached clients in Perl and other languages relies on internal 'user-defined' protocol flags. Meaning, that the flags are free for use by any client implementation. These flags are of course not exposed to you, the end user, but it's worth reading about them.

Legacy clients have used 'standard' flags for compression and serialization - flags which themselves only make sense to other hosts running the same client with the same understanding of the flag semantics.

What this means for you:

Storable-incompatibility and interoperability

When serializing a complex object, the default is to use Storable. Storable itself is ill-suited for cross-platform, cross-machine and cross-version storage.

Additionally, the flags set by other Perl clients to indicate Storable is the same flag used by other memcached clients in other languages to indicate other forms of serialization and/or compression.

Therefore it is highly unrecommended to use Storable if you want any other host to be able to access your key. If you are sure that all your hosts are running the same version of Storable on the same architecture then it might not fail.

Having said that, Storable is still enabled by default in order to retain drop-in compatibility with older clients.


Most clients have used the same flag to indicate Gzip compression. While legacy clients (Cache::Memcached and friends) provide options to provide your 'own' compression mechanism, this compression mechanism must be used throughout all hosts wishing to read and write to the key

Appending, Prepending

Compression and serialization are ill-suited for values which may be modified using "append" and "prepend". Specifically the server will blindly append the data provided (in byte form) to the already-stored value.

Now, without further ado, we present conversion options, mostly copy-pasted from Cache::Memcached::Fast

  compress_threshold => 10_000
  (default: -1)

The value is an integer. When positive it denotes the threshold size in bytes: data with the size equal or larger than this should be compressed. See "compress_ratio" and "compress_methods" below.

Non-positive value disables compression.

  compress_methods => [ \&IO::Compress::Gzip::gzip,
                        \&IO::Uncompress::Gunzip::gunzip ]
  (default: [ sub { ${$_[1]} = Compress::Zlib::memGzip(${$_[0]}) },
              sub { ${$_[1]} = Compress::Zlib::memGunzip(${$_[0]}) } ]
   when Compress::Zlib is available)

The value is a reference to an array holding two code references for compression and decompression routines respectively.

Compression routine is called when the size of the $value passed to "set" method family is greater than or equal to "compress_threshold". The fact that compression was performed is remembered along with the data, and decompression routine is called on data retrieval with "get" method family. The interface of these routines should be the same as for IO::Compress family (for instance see IO::Compress::Gzip::gzip and IO::Uncompress::Gunzip::gunzip). I.e. compression routine takes a reference to scalar value and a reference to scalar where compressed result will be stored. Decompression routine takes a reference to scalar with compressed data and a reference to scalar where uncompressed result will be stored. Both routines should return true on success, and false on error.

By default we use Compress::Zlib because as of this writing it appears to be much faster than IO::Uncompress::Gunzip.

  serialize_methods => [ \&Storable::freeze, \&Storable::thaw ],
  (default: [ \&Storable::nfreeze, \&Storable::thaw ])

The value is a reference to an array holding two code references for serialization and deserialization routines respectively.

Serialization routine is called when the $value passed to "set" method family is a reference. The fact that serialization was performed is remembered along with the data, and deserialization routine is called on data retrieval with "get" method family. The interface of these routines should be the same as for Storable::nfreeze and Storable::thaw. I.e. serialization routine takes a reference and returns a scalar string; it should not fail. Deserialization routine takes scalar string and returns a reference; if deserialization fails (say, wrong data format) it should throw an exception (call die). The exception will be caught by the module and "get" will then pretend that the key hasn't been found.

    deconversion => 1
    (default: deconversion => 1)

Controls whether de-compression and de-serialization are performed on apparently serialized or compressed values.

Default is enabled.

    dereference_scalar_ref => 1
    (default: dereference_scalar_ref => 0)

Controls whether a SCALAR reference is 'serialized' as normal via storable, or whether it should be dereferenced, and its underlying string used as a plain scalar value.


Retrieves the value stored under key. Returns an Couchbase::Client::Return object.

If the key is not found on the server, the returned object's errnum field will be set to COUCHBASE_KEY_ENOENT



set(key, value [,expiry])

Attempts to set, prepend, or append the value of the key key to value, optionally setting an expiration time of expiry seconds in the future.

Returns an Couchbase::Client::Return object.

add(key, value [,expiry])

Store the value on the server, but only if the key does not already exist.

A <COUCHBASE_KEY_EEXISTS> will be set in the returned object's errnum field if the key does already exist.

See "set" for explanation of arguments.

replace(key, value [,expiry])

Replace the value stored under key with value, but only if the key does already exist on the server.

See "get" for possible errors, and "set" for argument description.


This is an alias to "get". The CAS value is returned on any get operation.

cas(key, value, cas, [,expiry])

Tries to set the value of key to value but only if the opaque cas is equal to the CAS value on the server.

The <cas> argument is retrieved as such:

    my $opret = $client->get("Key");
    $client->set("Key", "Value", $opret->cas);

The last argument is the expiration offset as documented in "set"

touch(key, expiry)

Modifies the expiration time of key without fetching or setting it.

arithmetic(key, delta, initial [,expiry])

Performs an arithmetic operation on the numeric value stored in key.

The value will be added to delta (which may be a negative number, in which case, abs(delta) will be subtracted).

If initial is not undef, it is the value to which key will be initialized if it does not yet exist.

incr(key [,delta])

decr(key [,delta])

Increments or decrements the numeric value stored under key, if it exists.

If delta is specified, it is the absolute value to be added to or subtracted from the value. delta defaults to 1.

These two functions are equivalent to doing:

    $delta ||= 1;
    $delta = -$delta if $decr;
    $o->arithmetic($key, $delta, undef);


If Perl does not support 64 bit integers then the following will happen:

If the result of an arithmetic operation can be stored within a 32 bit integer, then all proceeds as normal and you get a normal Perl integer back. If, however the result exceeds 32 bits (i.e. greated than stdint.h's UINT32_MAX) then your return value will be stringified, since the underlying C layer can always deal with 64 bit integers.

delete(key [,cas])

remove(key [,cas])

These two functions are identical. They will delete key on the server.

If cas is also specified, the deletion will only be performed if key still maintains the same CAS value as cas.


These methods gain performance and save on network I/O by batch-enqueueing operations.

Of these, only the get and touch methods currently do 'true' multi batching.

The other commands are still batched internally in the XS code, saving on xsub call overhead.

All of these functions return a hash reference, whose keys are the keys specified for the operation, and whose values are Couchbase::Client::Return objects specifying the result of the operation for that key.

Calling the multi methods generally involves passing a series of array references. Each n-tuple passed in the list should contain arguments conforming to the calling convention of the non-multi command variant.

Thus, where you would do:

    $rv = $o->foo($arg1, $arg2, $arg3)

The _multi version would be

    $rvs = $o->foo_multi(
        [$arg1_0, $arg2_0, $arg3_0],
        [$arg1_1, $arg2_1, $arg3_1],

The n-tuples themselves may either be grouped into a 'list', or an array reference itself:

    my @arglist = map { [$h->{key}, $k->{value} ] };


    #the same as:

    $o->set( [ map [ { $h->{key}, $h->{value } ] }] );

    #and the same as:

    $o->set(map{ [$h->{key}, $h->{value}] });




alias to "get_multi"

touch_multi([key, exp]..)

set_multi([key => value, ...], [key => value, ...])

Performs multiple set operations on a multitude of keys. Input parameters are array references. The contents of these array references follow the same convention as calls to "set" do. Thus:

    $o->set_multi(['Foo', 'foo_value', 120], ['Bar', 'bar_value']);

will set the key foo to foo_value, with an expiry of 120 seconds in the future. bar is set to bar_value, without any expiry.

cas_multi([key => value, $cas, ...])

Multi version of "cas"

arithmetic_multi([key => $delta, ...])

Multi version of "arithmetic"



incr_multi( [key, amount], ... )

decr_multi( [key, amount], ... )


The following methods can be called without an argument, in which case it acts as a getter, and returns the boolean status of the relevant setting.

If called with a single argument, that argument is a boolean value and the method acts as a mutator. The old value for the setting is returned.

enable_compress(...), compression_settings(...)


These methods, when called with no arguments, will return the boolean status about whether compression or serialization is enabled.

If passed an argument, the argument is converted to a boolean value, and the previous setting is returned.

enable_compress is an alias to compression_settings, for API familiarity with older clients.


This is a catch-all setting for all modes of conversion; i.e. serialization and compression. Disabling conversion will disable compression and serialization.

Enabling conversion will restore the previous serialization and compression settings.


This controls and accesses the deconversion setting. Deconversion is any decompression or deserialization when retrieving a remote value. This can be particularly handy if you wish to perform more heuristics on the type of the value, rather than possibly have the deconversion settings fail.

When deconversion is disabled, all conversion settings are disabled as well.


Gets or sets the compression threshold, i.e. the minimum value length before compression is applied.


Get or set the timeout for enqueued operations. The timeout is the time the client waits for a response after sending the request to the server.

Timeouts cannot be disabled. See documentation on constructor options.



Returns a list of client/server errors which have ocurred during the last operation.

The errors here differ from the errors returned by normal operations, as the operation errors provide status for a specific key, whereas get_errors provide status for the client connection in general.

The return value is an arrayref of arrayrefs in the following format:

    get_errors() == [
        [$errnum, $errstr],
        [$errnum, $errstr],

Modifications to the arrayref returned by get_errors will be reflected in future calls to this function, until a new operation is performed and the error stack is cleared.

stats( [keys, ..] )


Get statistics from all servers in the cluster.

If [keys..] are specified, only the named keys will be gathered and returned

The return format is as so:

        'server_name' => {
            'key_name' => 'key_value',




Status codes and their meanings.

Couchbase::Client::Compat - subclass which conforms to the Cache::Memcached interface. - Couchbase.


Copyright (C) 2012 M. Nunberg

You may use and distributed this software under the same terms and conditions as Perl itself.