Concepts
Locks

Locking a backend to a resource

A common pattern is to have one session backend for each file or document that a user has open. In these cases, it is usually desirable to ensure that only one session backend is running per document, so that the backend can persist changes without worrying that the underlying data has changed in the meantime. Jamsocket's solution to this is locks.

A lock is a string that you pass to Jamsocket when you request a backend to be spawned. If no other currently-running backend was started with the same lock string, the backend will be spawned as usual. But if a backend was started with the same lock, the spawn request will return the details about that backend instead of spawning a new one.

A locks can be any (unicode) string up to 128 characters in length. Deciding how lock strings are generated is up to you, but we recommend using the canonical string representation of the resource that you are attempting to lock. For example, if you want to give a backend exclusive access to an S3 file, the lock could be the S3 URL of that file.

⚠️

Locks are shared across all your services

By default, locks are not namespaced by service. In most cases, you'll want to namespace locks with your service name (e.g. my-service/resource-123). If you want to ensure that only one backend across all your services has access to a resource, then it may make sense to share locks across all your services by not namespacing your locks.

A backend's lock may be found as the SESSION_BACKEND_KEY env var.

Example

Take the following spawn request, for example.

POST /user/my-account/service/my-service/spawn
{
  "lock": "my-service/document-123"
}

If no backend is currently running with the lock my-service/document-123, a new session backend will be spawned, and you'll receive a response that looks like this:

spawn-result-example
{
  "url": "https://8nyg2.p.jamsocket.net/eqYLfYmVbdIwSukbIxiFJNAjKz8KJLECmfYMQfqSgKs/",
  "name": "8nyg2",
  "ready_url": "https://api.jamsocket.com/ready/8nyg2/eqYLfYmVbdIwSukbIxiFJNAjKz8KJLECmfYMQfqSgKs/",
  "status_url": "https://api.jamsocket.com/backend/8nyg2/status",
  "spawned": true,
  "status": "Loading"
}

If, however, a running backend holds the lock my-service/document-123, a new backend will not be spawned. Instead, the running backend (in this case, 8nyg2) will be returned, and you'll receive a response that looks like this:

spawn-result-example
{
  "url": "https://8nyg2.p.jamsocket.net/eqYLfYmVbdIwSukbIxiFJNAjKz8KJLECmfYMQfqSgKs/",
  "name": "8nyg2",
  "ready_url": "https://api.jamsocket.com/ready/8nyg2/eqYLfYmVbdIwSukbIxiFJNAjKz8KJLECmfYMQfqSgKs/",
  "status_url": "https://api.jamsocket.com/backend/8nyg2/status",
  "spawned": false,
  "status": "Loading"
}
Jamsocket is built by Drifting in Space.