QuotaGuard and MongoDB Atlas Integration Guide
Table of contents
- QuotaGuard and MongoDB Atlas Integration Guide
- The Problem: Dynamic IPs and MongoDB Atlas Security
- Native Alternatives (When They Make Sense)
- Getting Started
- Configuring MongoDB Atlas IP Access List
- Configuring Your Application
- Using QGTunnel (Transparent Proxying)
- Testing Your Implementation
- Latency Considerations
- Troubleshooting
- Environment Variables Reference
- Security Best Practices
- QuotaGuard Static vs QuotaGuard Shield
- Ready to Get Started?
QuotaGuard and MongoDB Atlas Integration Guide
QuotaGuard Static IPs allow your cloud applications to connect to MongoDB Atlas through a load-balanced pair of static IP addresses. Once set up, you can add just two IPs to your Atlas IP Access List instead of opening your database to the entire internet.
You do not need QuotaGuard for local development or applications running on infrastructure with stable IPs. QuotaGuard is specifically for cloud platforms like Heroku, Render, Fly.io, serverless functions, and Kubernetes where outbound IPs are dynamic and unpredictable.
The Problem: Dynamic IPs and MongoDB Atlas Security
MongoDB Atlas requires every connecting IP address to be explicitly approved in the IP Access List. This is a critical security feature. The problem is that modern cloud platforms use dynamic, rotating IP addresses.
When your cloud application tries to connect to Atlas from an unapproved IP, you see errors like:
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster.
One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Or with the native driver:
MongoNetworkError: failed to connect to server [cluster0-shard-00-00.xxxxx.mongodb.net:27017]
on first connect [MongoNetworkError: connection timed out]
The Common (Bad) Workaround
Many developers add 0.0.0.0/0 to the IP Access List. This allows connections from any IP address on the internet.
This defeats the entire purpose of the IP Access List. Your database is now exposed to the world. Anyone with your connection string can attempt to connect. You are relying entirely on username/password authentication with no network-level protection.
MongoDB Atlas even warns you when you add this entry:
“Are you sure you want to allow access from anywhere? This is less secure than allowing specific IP addresses.”
Yet this workaround is extremely common because dynamic cloud IPs make proper allowlisting impossible without a solution like QuotaGuard.
The QuotaGuard Solution
Route your MongoDB connections through QuotaGuard’s SOCKS5 proxy. Your traffic exits from one of two static IP addresses. Add those two IPs to your Atlas IP Access List. Done.
- Your database is protected by network-level security
- No need to open to 0.0.0.0/0
- Works with any cloud platform
- Two permanent IPs to allowlist (load-balanced pair for high availability)
Native Alternatives (When They Make Sense)
MongoDB Atlas offers enterprise networking features that may fit certain architectures:
| Solution | Requirements | Best For |
|---|---|---|
| VPC Peering | M10+ cluster, same cloud provider and region | Large enterprise deployments already using VPCs |
| Private Endpoints | AWS PrivateLink, Azure Private Link, or GCP Private Service Connect | Enterprise with dedicated networking budgets |
| Network Peering | Dedicated cluster (M10+) | When all infrastructure is in the same cloud provider |
Use QuotaGuard instead when:
- You are on a free tier (M0), shared (M2/M5), or smaller dedicated cluster
- Your application runs on a platform that does not support VPC peering (Heroku, Render, Vercel, Netlify Functions)
- You need a quick solution without complex networking setup
- You are using serverless functions (Lambda, Cloud Functions) where VPC configuration adds cold start latency
- Your infrastructure spans multiple cloud providers
Getting Started
After creating a QuotaGuard account, you will be redirected to your dashboard where you can find your proxy credentials and static IP addresses.
Choose the right proxy region: Match your QuotaGuard region to your MongoDB Atlas cluster region for minimum latency.
| Atlas Region | QuotaGuard Region |
|---|---|
| AWS us-east-1 (N. Virginia) | US-East |
| AWS us-west-2 (Oregon) | US-West |
| AWS eu-west-1 (Ireland) | EU-West (Ireland) |
| AWS eu-central-1 (Frankfurt) | EU-Central (Frankfurt) |
| AWS ap-southeast-1 (Singapore) | AP-Southeast (Singapore) |
| AWS ap-northeast-1 (Tokyo) | AP-Northeast (Tokyo) |
| AWS ap-southeast-2 (Sydney) | Australia (Sydney) |
| GCP us-central1 | US-Central |
| GCP europe-west1 | EU-West (Ireland) |
| Azure eastus | US-East |
| Azure westeurope | EU-West (Ireland) |
To check your Atlas cluster region, go to your cluster’s Overview tab and look at the Region field.
Your QuotaGuard SOCKS5 credentials will look like this:
Host: us-east-static-01.quotaguard.com
Port: 1080
Username: your-username
Password: your-password
Finding Your Static IPs: Your two static IPs are displayed in the QuotaGuard dashboard. Both IPs are active simultaneously. Add both to your Atlas IP Access List.
Configuring MongoDB Atlas IP Access List
Step 1: Open Network Access Settings
- Log in to MongoDB Atlas
- Select your project
- In the left sidebar, click Network Access under Security
Step 2: Add QuotaGuard Static IPs
- Click Add IP Address
- Enter your first QuotaGuard static IP (e.g.,
52.34.188.175) - Add a comment like “QuotaGuard Static IP 1”
- Click Confirm
- Repeat for your second QuotaGuard static IP
Both IPs should now appear in your IP Access List with a green “Active” status.
Step 3: Remove 0.0.0.0/0 (If Present)
If you previously added 0.0.0.0/0 as a workaround:
- Find the entry in your IP Access List
- Click the trash icon to delete it
- Confirm deletion
Your database is now only accessible from your QuotaGuard static IPs (plus any other specific IPs you have allowlisted).
Configuring Your Application
MongoDB uses port 27017 and its own wire protocol. This requires a SOCKS5 proxy, not an HTTP proxy. QuotaGuard’s SOCKS5 proxy runs on port 1080.
Node.js with Mongoose
Install the SOCKS proxy agent:
npm install socks-proxy-agent
Configure Mongoose to use the proxy:
const mongoose = require('mongoose');
const { SocksProxyAgent } = require('socks-proxy-agent');
// Build SOCKS5 proxy URL from environment variables
const socksUrl = `socks5://${process.env.QUOTAGUARD_SOCKS_USER}:${process.env.QUOTAGUARD_SOCKS_PASS}@${process.env.QUOTAGUARD_SOCKS_HOST}:${process.env.QUOTAGUARD_SOCKS_PORT}`;
const agent = new SocksProxyAgent(socksUrl);
// Connect with the proxy agent
mongoose.connect(process.env.MONGODB_URI, {
// Pass the agent in the connection options
// Mongoose 6+ uses this format
}).then(() => {
console.log('Connected to MongoDB Atlas through QuotaGuard');
}).catch(err => {
console.error('Connection error:', err);
});
Note on Mongoose versions: The exact method for passing a custom agent varies by Mongoose and MongoDB driver version. For Mongoose 6+ with mongodb driver 4+, you may need to configure the agent at the topology level. Check your driver documentation for the exact syntax.
Node.js with Native MongoDB Driver
const { MongoClient } = require('mongodb');
const { SocksProxyAgent } = require('socks-proxy-agent');
const socksUrl = `socks5://${process.env.QUOTAGUARD_SOCKS_USER}:${process.env.QUOTAGUARD_SOCKS_PASS}@${process.env.QUOTAGUARD_SOCKS_HOST}:${process.env.QUOTAGUARD_SOCKS_PORT}`;
const agent = new SocksProxyAgent(socksUrl);
const client = new MongoClient(process.env.MONGODB_URI, {
// For mongodb driver 4.x+
// The agent configuration depends on your driver version
// See the mongodb driver documentation for your specific version
});
async function connect() {
try {
await client.connect();
console.log('Connected to MongoDB Atlas through QuotaGuard');
const db = client.db('mydb');
const collection = db.collection('users');
// Your database operations here
const users = await collection.find({}).limit(10).toArray();
console.log('Found users:', users.length);
} catch (err) {
console.error('Connection error:', err);
}
}
connect();
Python with PyMongo
Install PySocks for SOCKS5 support:
pip install pymongo PySocks
Configure the SOCKS proxy before creating the MongoClient:
import os
import socks
import socket
from pymongo import MongoClient
# Configure SOCKS5 proxy globally
socks.set_default_proxy(
socks.SOCKS5,
os.environ.get('QUOTAGUARD_SOCKS_HOST'),
int(os.environ.get('QUOTAGUARD_SOCKS_PORT', 1080)),
username=os.environ.get('QUOTAGUARD_SOCKS_USER'),
password=os.environ.get('QUOTAGUARD_SOCKS_PASS')
)
socket.socket = socks.socksocket
# Now create your MongoDB client
# All connections will route through the SOCKS5 proxy
client = MongoClient(os.environ.get('MONGODB_URI'))
# Test the connection
try:
# The ping command is cheap and doesn't require authentication
client.admin.command('ping')
print('Connected to MongoDB Atlas through QuotaGuard')
except Exception as e:
print(f'Connection error: {e}')
# Use your database
db = client['mydb']
users = db['users']
# Example query
for user in users.find().limit(10):
print(user)
Important: The socks.set_default_proxy() call affects all socket connections in your Python process. If you need to proxy only MongoDB connections, use a more targeted approach or separate your application logic.
Go with mongo-go-driver
Go’s MongoDB driver supports custom dialers. You can use a SOCKS5 dialer:
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/net/proxy"
)
func main() {
// Build SOCKS5 proxy dialer
socksHost := os.Getenv("QUOTAGUARD_SOCKS_HOST")
socksPort := os.Getenv("QUOTAGUARD_SOCKS_PORT")
socksUser := os.Getenv("QUOTAGUARD_SOCKS_USER")
socksPass := os.Getenv("QUOTAGUARD_SOCKS_PASS")
auth := &proxy.Auth{
User: socksUser,
Password: socksPass,
}
dialer, err := proxy.SOCKS5("tcp", fmt.Sprintf("%s:%s", socksHost, socksPort), auth, proxy.Direct)
if err != nil {
log.Fatal("Failed to create SOCKS5 dialer:", err)
}
// Create custom dialer function for MongoDB
customDialer := func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.Dial(network, address)
}
// Configure MongoDB client with custom dialer
clientOptions := options.Client().
ApplyURI(os.Getenv("MONGODB_URI")).
SetDialer(&customDialerWrapper{dial: customDialer})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal("Failed to connect:", err)
}
// Test the connection
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal("Failed to ping:", err)
}
fmt.Println("Connected to MongoDB Atlas through QuotaGuard")
// Use your database
collection := client.Database("mydb").Collection("users")
cursor, err := collection.Find(ctx, map[string]interface{}{})
if err != nil {
log.Fatal("Query error:", err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var result map[string]interface{}
cursor.Decode(&result)
fmt.Println(result)
}
}
// customDialerWrapper implements the options.ContextDialer interface
type customDialerWrapper struct {
dial func(ctx context.Context, network, address string) (net.Conn, error)
}
func (d *customDialerWrapper) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return d.dial(ctx, network, address)
}
Install the proxy package:
go get golang.org/x/net/proxy
Ruby with Mongoid
Ruby’s MongoDB driver can use SOCKS proxies through the socksify gem:
gem install mongo socksify
Configure in your application:
require 'mongo'
require 'socksify'
# Configure SOCKS proxy
socks_host = ENV['QUOTAGUARD_SOCKS_HOST']
socks_port = ENV['QUOTAGUARD_SOCKS_PORT'].to_i
socks_user = ENV['QUOTAGUARD_SOCKS_USER']
socks_pass = ENV['QUOTAGUARD_SOCKS_PASS']
# Set up SOCKS proxy with authentication
TCPSocket.socks_server = socks_host
TCPSocket.socks_port = socks_port
TCPSocket.socks_username = socks_user
TCPSocket.socks_password = socks_pass
# Connect to MongoDB
client = Mongo::Client.new(ENV['MONGODB_URI'])
# Test the connection
begin
client.database.command(ping: 1)
puts 'Connected to MongoDB Atlas through QuotaGuard'
rescue => e
puts "Connection error: #{e.message}"
end
# Use your database
db = client.database
users = db[:users]
users.find.limit(10).each do |user|
puts user
end
For Mongoid (Rails ORM), configure the SOCKS proxy in an initializer that runs before Mongoid connects:
# config/initializers/socks_proxy.rb
require 'socksify'
if ENV['QUOTAGUARD_SOCKS_HOST'].present?
TCPSocket.socks_server = ENV['QUOTAGUARD_SOCKS_HOST']
TCPSocket.socks_port = ENV['QUOTAGUARD_SOCKS_PORT'].to_i
TCPSocket.socks_username = ENV['QUOTAGUARD_SOCKS_USER']
TCPSocket.socks_password = ENV['QUOTAGUARD_SOCKS_PASS']
end
Java
Java’s MongoDB driver can use SOCKS proxies through system properties or a custom socket factory:
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class MongoDBConnection {
public static void main(String[] args) {
// Configure SOCKS proxy via system properties
String socksHost = System.getenv("QUOTAGUARD_SOCKS_HOST");
String socksPort = System.getenv("QUOTAGUARD_SOCKS_PORT");
String socksUser = System.getenv("QUOTAGUARD_SOCKS_USER");
String socksPass = System.getenv("QUOTAGUARD_SOCKS_PASS");
System.setProperty("socksProxyHost", socksHost);
System.setProperty("socksProxyPort", socksPort);
// Set up authentication for the SOCKS proxy
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestingHost().equals(socksHost)) {
return new PasswordAuthentication(socksUser, socksPass.toCharArray());
}
return null;
}
});
// Configure and create MongoDB client
String mongoUri = System.getenv("MONGODB_URI");
ConnectionString connectionString = new ConnectionString(mongoUri);
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
try (MongoClient client = MongoClients.create(settings)) {
// Test the connection
MongoDatabase database = client.getDatabase("mydb");
Document ping = database.runCommand(new Document("ping", 1));
System.out.println("Connected to MongoDB Atlas through QuotaGuard");
// Use your database
MongoCollection<Document> users = database.getCollection("users");
for (Document user : users.find().limit(10)) {
System.out.println(user.toJson());
}
} catch (Exception e) {
System.err.println("Connection error: " + e.getMessage());
}
}
}
Using QGTunnel (Transparent Proxying)
QGTunnel is a wrapper process that creates local port mappings. Your application connects to localhost, and QGTunnel handles the SOCKS5 proxying transparently. This approach requires no code changes.
Step 1: Download QGTunnel
curl https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz | tar xz
This creates bin/qgtunnel and supporting files in vendor/nss_wrapper/.
Step 2: Configure Tunnel in QuotaGuard Dashboard
- Open your QuotaGuard dashboard
- Navigate to Settings > Setup > Tunnel > Create Tunnel
- Configure for MongoDB Atlas:
| Setting | Value |
|---|---|
| Remote Destination | tcp://cluster0-shard-00-00.xxxxx.mongodb.net:27017 |
| Local Port | 27017 |
| Transparent | false |
| Encrypted | false |
Important: You need to create a tunnel entry for each shard/node in your Atlas cluster. For a replica set with 3 nodes, create 3 tunnel entries.
To find your cluster hostnames:
- In Atlas, click Connect on your cluster
- Select Connect your application
- The connection string contains hostnames like
cluster0-shard-00-00.xxxxx.mongodb.net
Step 3: Download Configuration File
- In your QuotaGuard dashboard, go to Tunnel > Download configuration
- Save as
.qgtunnelin your project root
Step 4: Update Your Connection String
With QGTunnel in non-transparent mode, modify your MongoDB connection string to use localhost:
Original (Atlas connection string):
mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net/mydb
Modified (connecting through QGTunnel):
mongodb://user:pass@localhost:27017/mydb?directConnection=true
Note: When using QGTunnel, you typically connect directly to a single node rather than using the mongodb+srv:// connection string format. This is because QGTunnel maps specific remote hosts to local ports.
Step 5: Run Your Application with QGTunnel
Development:
bin/qgtunnel node server.js
Heroku (Procfile):
web: bin/qgtunnel node server.js
Docker:
ENTRYPOINT ["/app/bin/qgtunnel"]
CMD ["node", "server.js"]
When to Use QGTunnel vs Direct SOCKS Configuration
| Approach | Best For |
|---|---|
| Direct SOCKS in code | Single database connection, modern driver with good proxy support |
| QGTunnel | Multiple databases, legacy code, languages without good SOCKS library support |
Testing Your Implementation
Verify MongoDB Connection
Once configured, test that your connection works:
Node.js:
const { MongoClient } = require('mongodb');
async function testConnection() {
const client = new MongoClient(process.env.MONGODB_URI);
try {
await client.connect();
await client.db('admin').command({ ping: 1 });
console.log('Successfully connected to MongoDB Atlas through QuotaGuard');
} catch (err) {
console.error('Connection failed:', err.message);
} finally {
await client.close();
}
}
testConnection();
Python:
from pymongo import MongoClient
import os
client = MongoClient(os.environ.get('MONGODB_URI'))
try:
client.admin.command('ping')
print('Successfully connected to MongoDB Atlas through QuotaGuard')
except Exception as e:
print(f'Connection failed: {e}')
Verify IP Address (Optional)
To confirm traffic routes through QuotaGuard, you can check what IP address your application appears to have. This is tricky with MongoDB directly, but you can verify using an HTTP endpoint in the same runtime:
import requests
import os
# Using your same application's outbound IP check
proxy_url = os.environ.get('QUOTAGUARDSTATIC_URL')
proxies = {'http': proxy_url, 'https': proxy_url}
response = requests.get('https://ip.quotaguard.com', proxies=proxies)
print(f'Your outbound IP: {response.json()["ip"]}')
The IP should match one of your QuotaGuard static IPs shown in the dashboard.
Latency Considerations
Using QuotaGuard adds a network hop to your database connections:
| Configuration | Added Latency |
|---|---|
| Same region (App + QuotaGuard + Atlas in us-east-1) | 5-15ms |
| Cross-region | 50-150ms |
MongoDB operations are typically sensitive to latency. For best performance:
- Match all three regions: Your application, QuotaGuard proxy, and Atlas cluster should all be in the same region
- Use connection pooling: Let your MongoDB driver maintain persistent connections rather than reconnecting for each operation
- Consider read preferences: For read-heavy workloads, configure read preferences appropriately
For most applications, the 5-15ms added latency is negligible compared to query execution time and network variability.
Troubleshooting
MongoServerSelectionError: Could not connect to any servers
Symptoms:
MongoServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster.
One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Causes and solutions:
- QuotaGuard IPs not added to Atlas: Verify both IPs are in your IP Access List with “Active” status
- Wrong SOCKS port: QuotaGuard SOCKS is on port 1080, not 9293 (HTTP proxy port)
- SOCKS proxy not configured in code: Verify your proxy configuration is actually being applied
- 0.0.0.0/0 removed but QuotaGuard IPs not added yet: Add the IPs before removing the wildcard
Authentication Failed
Symptoms:
MongoError: Authentication failed
This is a MongoDB authentication error, not a proxy issue. Verify:
- Your MongoDB username and password are correct
- The user has access to the database you are connecting to
- The authentication database is correct (usually
admin)
Connection Timeout
Symptoms:
MongoNetworkError: connection timed out
Causes and solutions:
- Wrong QuotaGuard region: If your proxy is in a different region than Atlas, timeouts may occur. Match regions.
- SOCKS credentials incorrect: Double-check username and password
- Firewall blocking port 1080: Ensure your application can reach QuotaGuard on port 1080
SOCKS Proxy Authentication Required
Symptoms:
Error: SOCKS authentication failed
Causes:
- Username or password is incorrect
- Credentials contain special characters that need encoding
- Wrong SOCKS version (use SOCKS5, not SOCKS4)
QGTunnel: Configuration Not Found
Symptoms:
qgtunnel: error: configuration file not found
Solution:
- Verify
.qgtunnelfile exists in your project root - Check file permissions
- For production, consider downloading the config file rather than relying on API fetch at startup
QGTunnel: Connection Refused to localhost
Symptoms:
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
Causes:
- QGTunnel is not running or not started properly
- Tunnel configuration does not include the correct local port
- Application started before QGTunnel finished initialization
Solution: Ensure QGTunnel is the entrypoint for your process so it starts before your application code runs.
Environment Variables Reference
Set these environment variables in your application:
# For HTTP proxy (port 9293) - used for HTTP/HTTPS requests
QUOTAGUARDSTATIC_URL=http://username:password@us-east-static-01.quotaguard.com:9293
# For SOCKS5 proxy (port 1080) - used for MongoDB and other TCP connections
QUOTAGUARD_SOCKS_HOST=us-east-static-01.quotaguard.com
QUOTAGUARD_SOCKS_PORT=1080
QUOTAGUARD_SOCKS_USER=your-username
QUOTAGUARD_SOCKS_PASS=your-password
# Your MongoDB Atlas connection string
MONGODB_URI=mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net/mydb?retryWrites=true&w=majority
Security Best Practices
- Never commit credentials to source control: Use environment variables or secrets management
- Remove 0.0.0.0/0 from your IP Access List: The whole point is to avoid this
- Use database user permissions: Grant only the permissions each user needs
- Enable Atlas audit logging: Track who accesses your database and when
- Rotate credentials periodically: Both MongoDB and QuotaGuard credentials
QuotaGuard Static vs QuotaGuard Shield
QuotaGuard offers two products:
| Feature | QuotaGuard Static | QuotaGuard Shield |
|---|---|---|
| Protocol | HTTP/SOCKS5 | HTTPS/SOCKS5 over TLS |
| Encryption | Standard proxy | SSL Passthrough (E2EE) |
| Best for | General database access | HIPAA, PCI-DSS, regulated data |
| Starting price | $19/month | $69/month |
MongoDB Atlas connections are already encrypted with TLS. QuotaGuard Static is sufficient for most use cases. Choose Shield if your compliance requirements mandate end-to-end encryption through all intermediary systems.
Ready to Get Started?
Stop using 0.0.0.0/0. Get proper network security for your MongoDB Atlas cluster.
View MongoDB Integration Features