Databases & Caching

NoSQL Setup & Deployment Guide

Understand document, key-value, wide-column and graph databases, model data for them, and run one locally and in production.

Updated Official documentation ↗

1. Introduction & use cases

NoSQL (“not only SQL”) databases store data in models other than the relational tables of MySQL or PostgreSQL. They trade some features (fixed schemas, multi-table joins) for flexible schemas, horizontal scaling and very fast access patterns.

There are four main families: document stores (MongoDB, Firestore), key-value stores (Redis, DynamoDB), wide-column stores (Cassandra, ScyllaDB) and graph databases (Neo4j). Choose by how your application reads data, not by trend – many systems use SQL and NoSQL together.

Where it is used

  • Product catalogues and content with varying fields (document)
  • Caching, sessions, rate limits, leaderboards (key-value)
  • Time-series, IoT and event logs at huge scale (wide-column)
  • Recommendations, fraud detection, social graphs (graph)

2. Prerequisites

You needVersion / notes
Docker (recommended)Docker Desktop or Docker Engine to run the database locally – see the Docker guide
Client toolsmongosh / MongoDB Compass, redis-cli / Redis Insight
BasicsJSON and how your app queries data

3. Local setup

  1. 1Pick the right type

    Use this table to choose. If you need complex joins and strict transactions across many tables, a relational database is usually the better default.

    OUTPUT
    Need                                   Good fit
    -------------------------------------  -----------------------------
    Flexible JSON-like records              Document  (MongoDB)
    Very fast lookups by key / caching      Key-value (Redis, DynamoDB)
    Massive write volume, time-series       Wide-column (Cassandra)
    Relationships are the data              Graph     (Neo4j)
  2. 2Run a document and a key-value store with Docker

    One command each – no installation on your machine. Data is kept in named volumes.

    BASH
    docker run -d --name mongo -p 27017:27017 -v mongo-data:/data/db mongo:8
    docker run -d --name redis -p 6379:6379 -v redis-data:/data redis:7
    docker ps
  3. 3Connect with the shells

    Check both are working.

    BASH
    docker exec -it mongo mongosh --eval "db.runCommand({ ping: 1 })"
    docker exec -it redis redis-cli PING

4. Create & run a project

  1. 1Model data the NoSQL way

    In a document database you embed data that is read together, instead of splitting it into many tables. One order document holds its items:

    JSON
    {
      "_id": "ord_1001",
      "customer": { "id": "c_7", "name": "Asha" },
      "items": [
        { "sku": "PEN-01", "qty": 2, "price": 25 },
        { "sku": "NB-A5",  "qty": 1, "price": 80 }
      ],
      "total": 130,
      "status": "paid",
      "createdAt": "2026-12-04T10:00:00Z"
    }
  2. 2Store and query it in MongoDB

    Insert the document and query by a nested field.

    JS
    docker exec -it mongo mongosh shop
    
    db.orders.insertOne({ _id: 'ord_1001', customer: { id: 'c_7', name: 'Asha' }, items: [{ sku: 'PEN-01', qty: 2, price: 25 }], total: 130, status: 'paid' })
    db.orders.find({ 'customer.id': 'c_7' })
    db.orders.createIndex({ 'customer.id': 1 })
  3. 3Cache the result in Redis

    Key-value stores are perfect for short-lived copies of expensive results. EX 60 expires the key after 60 seconds.

    BASH
    docker exec -it redis redis-cli
    SET customer:c_7:orders '["ord_1001"]' EX 60
    GET customer:c_7:orders
    TTL customer:c_7:orders

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Keep connection strings in environment variables; they often contain passwords.

.env
MONGODB_URI=mongodb://localhost:27017/shop
REDIS_URL=redis://localhost:6379

Key dependencies

Package / toolUsed for
MongoDB + driver/ODMDocument database (mongodb, Mongoose, PyMongo)
Redis + clientKey-value store (redis, ioredis, redis-py)
DynamoDBManaged key-value/document on AWS
Cassandra / ScyllaDBWide-column at large scale
Neo4jGraph database with Cypher queries

Folder structure

project structure
app/
├── src/
│   ├── db/
│   │   ├── mongo.js     # one shared client
│   │   └── redis.js
│   └── repositories/    # data access per collection
├── docker-compose.yml  # local databases
└── .env

Essential commands

CommandWhat it does
docker run … mongo:8Start MongoDB locally
docker run … redis:7Start Redis locally
mongoshMongoDB shell
redis-cliRedis shell
db.collection.createIndex()Add an index for a query pattern

6. Production deployment

For most teams a managed service is the safest production choice – backups, patches, replication and monitoring are handled for you: MongoDB Atlas, Amazon DynamoDB, Amazon ElastiCache/Valkey or Redis Cloud, Amazon Keyspaces. Self-hosting is possible but you own security and backups.

Server & hosting requirements

RequirementRecommendation
Option A – managedAtlas / DynamoDB / ElastiCache in the same region as your app
Option B – self-hostedVPS with SSD, enough RAM for the working set, replica set / persistence enabled
NetworkPrivate network or IP allow-list; never open DB ports to the internet
BackupsAutomated snapshots + tested restores

Deployment steps

  1. 1Decide your access patterns first

    List the queries your app runs and design keys/indexes for them before going live – NoSQL schemas are shaped by reads.

  2. 2Create a managed cluster

    In the provider console choose the region close to your servers, the smallest tier that fits, and enable automatic backups. (Step-by-step: MongoDB, Redis.)

  3. 3Lock down access

    Create a database user with only the rights the app needs and allow connections only from your servers’ IPs or VPC.

  4. 4Store the connection string as a secret

    Put it in the server’s environment or a secret manager – not in code.

    OUTPUT
    # on the server
    MONGODB_URI=mongodb+srv://app:***@cluster0.xxxxx.mongodb.net/shop
    REDIS_URL=rediss://default:***@your-cache.example.com:6379
  5. 5Monitor and test backups

    Watch latency, connections and storage in the provider dashboard and restore a backup to a test environment at least once.

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ docker exec -it mongo mongosh --eval "db.runCommand({ ping: 1 })"{ ok: 1 }$ docker exec -it redis redis-cli PINGPONG$ redis-cli GET customer:c_7:orders"[\"ord_1001\"]"
Figure 1: terminal output of the sample NoSQL project (section 4).
1Model accesspatterns2Local Docker DB3Managed cluster4Private network +user5App via secret URI
Figure 2: production deployment flow (section 6).
app/├── src/│ ├── db/│ │ ├── mongo.js # one shared client│ │ └── redis.js│ └── repositories/ # data access per collection├── docker-compose.yml # local databases└── .env
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Queries get slow as data grows

Missing index for the query pattern. Use explain() (MongoDB) and add indexes for the fields you filter and sort on.

Documents keep growing without limit

Unbounded arrays (e.g. all comments inside a post) hit size limits. Store such lists in a separate collection and reference them.

Data inconsistency between copies

Embedding duplicates data. Update all copies in one transaction or accept eventual consistency deliberately.

Database exposed to the internet / ransom note

Never bind to 0.0.0.0 without authentication and firewall rules. Use private networking and strong credentials.

Best practices

  • Design around queries, not around entities.
  • Use SQL where you need joins and strict relational integrity; NoSQL where flexibility and scale matter.
  • Index deliberately and review slow-query logs.
  • Prefer managed services for production.
  • Never commit .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.