{"id":21029385,"url":"https://github.com/stoqey/serverless-couchbase","last_synced_at":"2025-06-14T05:04:21.694Z","repository":{"id":57163030,"uuid":"335113533","full_name":"stoqey/serverless-couchbase","owner":"stoqey","description":"A module for managing Couchbase connections at a serverless scale.","archived":false,"fork":false,"pushed_at":"2021-02-02T10:18:40.000Z","size":882,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-06-01T14:39:44.485Z","etag":null,"topics":["aws-lambda","connection-reuse","couchbase","couchbase-server","jitter","retry-connections","serverless","serverless-functions","sofa","transaction"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stoqey.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":"ceddybi","patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2021-02-01T23:32:53.000Z","updated_at":"2022-07-29T22:38:32.000Z","dependencies_parsed_at":"2022-09-01T00:20:17.623Z","dependency_job_id":null,"html_url":"https://github.com/stoqey/serverless-couchbase","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/stoqey/serverless-couchbase","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fserverless-couchbase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fserverless-couchbase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fserverless-couchbase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fserverless-couchbase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stoqey","download_url":"https://codeload.github.com/stoqey/serverless-couchbase/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fserverless-couchbase/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259410149,"owners_count":22852970,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws-lambda","connection-reuse","couchbase","couchbase-server","jitter","retry-connections","serverless","serverless-functions","sofa","transaction"],"created_at":"2024-11-19T12:12:07.360Z","updated_at":"2025-06-14T05:04:21.643Z","avatar_url":"https://github.com/stoqey.png","language":"TypeScript","funding_links":["https://github.com/sponsors/ceddybi"],"categories":[],"sub_categories":[],"readme":"# Serverless couchbase\n[![Serverless Couchbase](./docs/serverless-couchbase.png)](https://github.com/stoqey/serverless-couchbase/)\n\n[![npm](https://img.shields.io/npm/v/serverless-couchbase.svg)](https://www.npmjs.com/package/@stoqey/serverless-couchbase)\n[![npm](https://img.shields.io/npm/l/@stoqey/serverless-couchbase.svg)](https://www.npmjs.com/package/@stoqey/serverless-couchbase)\n\n### A module for managing Couchbase connections at *serverless* scale.\n\nServerless Couchbase is a wrapper for Stoqey's amazing **[Sofa](https://github.com/stoqey/sofa)** Node.js module. Normally, using the `couchbase` module with Node apps would be just fine. However, serverless functions (like AWS Lambda, Google Cloud Functions, and Azure Functions) scale almost infinitely by creating separate instances for each concurrent user. This is a **MAJOR PROBLEM** for DBs solutions like Couchbase, because available connections can be quickly maxed out by competing functions. Not anymore. 😀\n\nServerless Couchbase adds a connection management component to the `couchbase` module that is designed specifically for use with serverless applications. This module constantly monitors the number of connections being utilized, and then based on your settings, manages those connections to allow thousands of concurrent executions to share them. It will clean up zombies, enforce connection limits per user, and retry connections using trusted backoff algorithms.\n\n**NOTE:** This module *should* work with any standards-based Couchbase server..\n\n## Simple Example\n\n```javascript\nconst {  startCouchbase, query } = require('serverless-couchbase');\n\n\n// Require and initialize outside of your main handler\nconst config = {\n    connectionString: string;\n    bucketName: string; // process.env.COUCHBASE_BUCKET,\n    username: string;\n    password: string;\n};\nstartCouchbase(config);\n\n// Main handler function\nexports.handler = async (event, context) =\u003e {\n  // Run your query\n  let results = await query('SELECT * FROM table')\n\n  // Return the results\n  return results\n}\n```\n\n## Installation\n```\nnpm i serverless-couchbase\n```\n\n## Requirements\n- Node 8.10+\n- Couchbase server/cluster\n\n## Considerations for this module\n- Return promises for easy async request handling\n- Exponential backoff (using [Jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)) to handle failed connections\n- Monitor active connections and disconnect if more than X% of connections are being used\n- Support transactions\n- Support JIT connections\n- Assume AWS endorsed best practices from [here](https://github.com/aws-samples/aws-appsync-rds-aurora-sample/blob/master/src/lamdaresolver/index.js)\n\n## How to use this module\nServerless Couchbase wraps the **[sofa](https://github.com/stoqey/sofa)** module, so this module supports pretty much everything that the `couchbase` module does. It uses all the same connection options, provides a `query()` method that accepts the same arguments when [performing queries](https://github.com/stoqey/sofa#queries) (except the callback), and passes back the query results exactly as the `couchbase` module returns them. There are a few things that don't make sense in serverless environments, like streaming rows, so there is no support for that yet.\n\nTo use Serverless Couchbase, require it **OUTSIDE** your main function handler. This will allow for connection reuse between executions. The module must be initialized before its methods are available. [Configuration options](#configuration-options) must be passed in during initialization.\n\n```javascript\n// Require and initialize with default options\nconst {ServerlessCouchbase} = require('serverless-couchbase') \n\nconst couchbase = ServerlessCouchbase.Instance; // \u003c-- initialize with Instance\n\n// include configuration options\ncouchbase.config({\n  backoff: 'decorrelated',\n  base: 5,\n  cap: 200\n})\n```\n\nCouchbase connection options can be passed in at initialization or later using the `config()` method.\n\n```javascript\ncouchbase.config({\n  connectionString: string;\n  bucketName: string; // process.env.COUCHBASE_BUCKET,\n  username: string;\n  password: string;\n})\n```\n\nYou can explicitly establish a connection using the `connect()` method if you want to, though it isn't necessary. This method returns a promise, so you'll need to `await` the response or wrap it in a promise chain.\n\n```javascript\nawait couchbase.connect()\n```\n\nRunning queries is super simple using the `query()` method. It supports all [query options](https://github.com/stoqey/sofa#performing-queries) supported by the `couchbase` module, but returns a promise instead of using the standard callbacks. You either need to `await` them or wrap them in a promise chain.\n\n```javascript\n// Simple query\nlet results = await query('SELECT * FROM table')\n\n// Query with placeholder values\nlet results = await query('SELECT * FROM table WHERE name = ?')\n\n// Query with advanced options\nlet results = await query({\n  sql: 'SELECT * FROM table WHERE name = ?',\n  timeout: 10000\n  )\n})\n```\n\nOnce you've run all your queries and your serverless function is ready to return data, call the `end()` method to perform connection management. This will do things like check the current number of connections, clean up zombies, or even disconnect if there are too many connections being used. Be sure to `await` its results before continuing.\n\n```javascript\n// Perform connection management tasks\nawait couchbase.end()\n```\n\nNote that `end()` will **NOT** necessarily terminate the connection. Only if it has to to manage the connections. If you'd like to explicitly terminate connections, use the `quit()` method.\n\n```javascript\n// Gracefully terminate the connection\ncouchbase.quit()\n```\n\nIf you need access to the `connection` object, you can use the `getClient()` method. This will allow you to use any supported feature of the `couchbase` module directly.\n\n```javascript\n// Connect to your Couchbase instance first\nawait couchbase.connect()\n// Get the connection object\nlet connection = couchbase.getClient()\n\n```\n\n## Configuration Options\nBelow is a table containing all of the possible configuration options for `serverless-couchbase`. Additional details are provided throughout the documentation.\n\n| Property | Type | Description | Default |\n| -------- | ---- | ----------- | ------- |\n| library | `Function` | Custom couchbase ORM library | `@stoqey/sofa` |\n| backoff | `String` or `Function` | Backoff algorithm to be used when retrying connections. Possible values are `full` and `decorrelated`, or you can also specify your own algorithm. See [Connection Backoff](#connection-backoff) for more information.  | `full` |\n| base | `Integer` | Number of milliseconds added to random backoff values. | `2` |\n| cap | `Integer` | Maximum number of milliseconds between connection retries. | `100` |\n| config | `Object` | A `couchbase` configuration object as defined [here](https://github.com/stoqey/sofa#connection-options) | `{}` |\n| connUtilization | `Number` | The percentage of total connections to use when connecting to your Couchbase server. A value of `0.75` would use 75% of your total available connections. | `0.8` |\n| manageConns | `Boolean` | Flag indicating whether or not you want `serverless-couchbase` to manage Couchbase connections for you. | `true` |\n| maxConnsFreq | `Integer` | The number of milliseconds to cache lookups of @@max_connections. | `15000` |\n| maxRetries | `Integer` | Maximum number of times to retry a connection before throwing an error. | `50` |\n| onError | `function` | [Event](#events) callback when the Couchbase connection fires an error. | |\n| onClose | `function` | [Event](#events) callback when Couchbase connections are explicitly closed. | |\n| onConnect | `function` | [Event](#events) callback when connections are succesfully established. | |\n| onConnectError | `function` | [Event](#events) callback when connection fails. | |\n| onKill | `function` | [Event](#events) callback when connections are explicitly killed. | |\n| onKillError | `function` | [Event](#events) callback when a connection cannot be killed. | |\n| onRetry | `function` | [Event](#events) callback when connections are retried. | |\n| usedConnsFreq | `Integer` | The number of milliseconds to cache lookups of current connection usage. | `0` |\n| zombieMaxTimeout | `Integer` | The maximum number of seconds that a connection can stay idle before being recycled. | `900` |\n| zombieMinTimeout | `Integer` | The minimum number of *seconds* that a connection must be idle before the module will recycle it. | `3` |\n\n### Connection Backoff\nIf `manageConns` is not set to `false`, then this module will automatically kill idle connections or disconnect the current connection if the `connUtilization` limit is reached. Even with this aggressive strategy, it is possible that multiple functions will be competing for available connections. The `backoff` setting uses the strategy outlined [here](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/) to use *Jitter* instead of *Exponential Backoff* when attempting connection retries.\n\nThe two supported methods are `full` and `decorrelated` Jitter. Both are effective in reducing server strain and minimize retries. The module defaults to `full`.\n\n**Full Jitter:** LESS work, MORE time\n```javascript\nsleep = random_between(0, min(cap, base * 2 ** attempts))\n```\n\n**Decorrelated Jitter:** MORE work, LESS time\n```javascript\nsleep = min(cap, random_between(base, sleep * 3))\n```\n\nIn addition to the two built-in algorithms, you can also provide your own by setting the value of `backoff` to an anonymous function. The function will receive the last `wait` value (how long the previous connection delay was) and `retries` (the number of retries attempted). Your function must return an `Integer` that represents the number of milliseconds to delay the next retry.\n\n```javascript\nbackoff: (wait,retries) =\u003e {\n  console.log('CUSTOM BACKOFF',wait,retries)\n  return 20 // return integer\n}\n```\n\n\n## Events\nThe module fires seven different types of events: `onConnect`, `onConnectError`, `onRetry`, `onClose`, `onError`, `onKill`, and `onKillError`. These are *reporting* events that allow you to add logging or perform additional actions. You could use these events to short-circuit your handler execution, but using `catch` blocks is preferred. For example, `onError` and `onKillError` are not fatal and will be handled by `serverless-couchbase`. Therefore, they will **NOT** `throw` an error and trigger a `catch` block.\n\nError events (`onConnectError`, `onError` and `onKillError`) all receive one argument containing the `couchbase` module error object.\n\n```javascript\nonConnectError: (e) =\u003e { console.log('Connect Error: ' + e.code) }\n```\n\nThe `onConnect` event recieves the Couchbase `connection` object, `onKill` receives the `threadId` of the connection killed, and `onClose` doesn't receive any arguments.\n\n`onRetry` receives *four* arguments. The `error` object, the number of `retries`, the `delay` until the next retry, and the `backoff` algorithm used (`full`, `decorrelated` or `custom`).\n\n```javascript\nonRetry: (err,retries,delay,type) =\u003e { console.log('RETRY') }\n```\n\n## Couchbase Server Configuration\nThere really isn't anything special that needs to be done in order for your Couchbase server (including AWS lambda, GCP functions/Firebase, Azure) to use `serverless-couchbase`. You should just be aware of the following two scenarios.\n\n## Query Timeouts\nThe `couchbase` module allows you to specify a \"[timeout](https://github.com/stoqey/sofa#timeouts)\" with each query. Typically this will disconnect the connection and prevent you from running additional queries. `serverless-couchbase` handles timeouts a bit more elegantly by throwing an error and `destroy()`ing the connection. This will reset the connection completely, allowing you to run additional queries **AFTER** you catch the error.\n\n## Transaction Support\nTransaction support in `serverless-couchbase` has been dramatically simplified. Start a new transaction using the `transaction()` method, and then chain queries using the `query()` method. The `query()` method supports all standard query options. Alternatively, you can specify a function as the only argument in a `query()` method call and return the arguments as an array of values. The function receives two arguments, the result of the last query executed and an array containing all the previous query results. This is useful if you need values from a previous query as part of your transaction.\n\nYou can specify an optional `rollback()` method in the chain. This will receive the `error` object, allowing you to add additional logging or perform some other action. Call the `commit()` method when you are ready to execute the queries.\n\n```javascript\nlet results = await couchbase.transaction()\n  .query('INSERT INTO table (x) VALUES(?)', [1])\n  .query('UPDATE table SET x = 1')\n  .rollback(e =\u003e { /* do something with the error */ }) // optional\n  .commit() // execute the queries\n```\n\nWith a function to get the `insertId` from the previous query:\n\n```javascript\nlet results = await couchbase.transaction()\n  .query('INSERT INTO table (x) VALUES(?)', [1])\n  .query((r) =\u003e ['UPDATE table SET x = 1 WHERE id = ?', r.insertId])\n  .rollback(e =\u003e { /* do something with the error */ }) // optional\n  .commit() // execute the queries\n```\n\nYou can also return a `null` or empty response from `.query()` calls within a transaction. This lets you perform conditional transactions like this:\n\n```javascript\nlet results = await couchbase.transaction()\n  .query('DELETE FROM table WHERE id = ?', [someVar])\n  .query((r) =\u003e {\n    if (r.affectedRows \u003e 0) {\n      return ['UPDATE anotherTable SET x = 1 WHERE id = ?', [someVar]]\n    } else {\n      return null\n    }\n  })\n  .rollback(e =\u003e { /* do something with the error */ }) // optional\n  .commit() // execute the queries\n```\n\n\n## Reusing Persistent Connections\nIf you're using AWS Lambda with **callbacks**, be sure to set `context.callbackWaitsForEmptyEventLoop = false;` in your main handler. This will allow the freezing of connections and will prevent Lambda from hanging on open connections. See [here](https://www.jeremydaly.com/reuse-database-connections-aws-lambda/) for more information. If you are using `async` functions, this is no longer necessary.\n\n## Sponsors\n\n# STQ\n\u003cimg width=\"200\" src=\"./docs/STQ.png\"\u003e\u003c/img\u003e\n\n\n\u003c!-- Package tracking --\u003e\n\u003c!-- \u003cIMG SRC=\"https://ad.doubleclick.net/ddm/trackimp/N1116303.3950900PODSEARCH.COM/B24770737.285235234;dc_trk_aid=479074825;dc_trk_cid=139488579;ord=[timestamp];dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755}?\" BORDER=\"0\" HEIGHT=\"1\" WIDTH=\"1\" ALT=\"Advertisement\"\u003e --\u003e\n\n## Contributions\nContributions, ideas and bug reports are welcome and greatly appreciated. Please add [issues](https://github.com/stoqey/serverless-couchbase/issues) for suggestions and bug reports or create a pull request.\n\n\n## TODO\n- Add defaults \n- Tests\n- Test module\n- Use ping to check already connected\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstoqey%2Fserverless-couchbase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstoqey%2Fserverless-couchbase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstoqey%2Fserverless-couchbase/lists"}