To handle simultaneous requests for the same browser session, keep the session state somewhere every relevant worker can access, then serialize any non-atomic read-modify-write operation. In OpenResty/ngx_lua, lua_shared_dict shares data across workers in one Nginx server instance; lua-resty-lock can lock a session key across those workers. Neither provides cluster-wide state or locking across multiple hosts.
First decide what must be shared and what must be serialized
“Concurrent browser sessions” often means several requests carrying the same session identity arrive before earlier requests finish. If they only read state, they may not need a lock. If they each read a value, change it, and write it back, they can overwrite one another unless the operation is atomic or serialized.
State location and concurrency control are separate decisions: a lock does not store the session, and a shared store does not automatically make every multi-step update safe.
| Mechanism | Scope | Good fit | Important limit |
|---|---|---|---|
| Request-local Lua values | One request | Temporary values used during a request | Not available to other requests |
| Lua module-level variables | One Nginx worker | Read-only or worker-local data | Different workers have different module state; mutable data is risky if execution yields mid-operation |
lua_shared_dict |
Workers in one Nginx server instance | Shared counters, caches, or state accessed by those workers | Does not share data with other hosts; atomic dictionary operations do not make arbitrary multi-step logic atomic |
lua-resty-lock |
Workers in one Nginx server instance | Serializing a short critical section for a key | It coordinates access; it is not the session store and does not coordinate separate hosts |
| External session store or coordination service | Potentially multiple application instances, depending on its design | State and coordination needed across hosts | Use the backend’s documented consistency and failure semantics; local shared memory is not a substitute |
limit_conn or resty.limit.conn |
As configured by the limiter | Controlling simultaneous request load | Admission control does not prevent two accepted requests from overwriting the same session update |
OpenResty’s official article “How to Share Data Between Requests in OpenResty,” updated July 7, 2026, distinguishes worker-local Lua module state from shared dictionaries. Its lua-nginx-module documentation describes shared-dictionary operations, including atomic operations such as incr. These are OpenResty/ngx_lua facilities; a plain NGINX installation does not imply they are installed.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Configure shared state and a lock dictionary
Declare dictionaries in the Nginx http context. The application dictionary stores the demo session counter; the second dictionary stores lock entries for lua-resty-lock. Choose sizes using expected data volume and observe memory use and eviction behavior under the real workload; there is no universal size that fits every session schema.
http {
lua_shared_dict sessions 10m;
lua_shared_dict session_locks 1m;
server {
listen 8080;
location /session-counter {
content_by_lua_file /etc/nginx/lua/session_counter.lua;
}
}
}
The sizes above are illustrative configuration values, not sizing recommendations. Install and load compatible OpenResty/ngx_lua and lua-resty-lock versions in the deployed environment. Verify the library API and Lua execution-phase support against those versions before deployment.
Serialize a session update with lua-resty-lock
This example assumes an upstream component has already validated the browser’s session cookie and that its value uses letters, digits, underscores, or hyphens. It stores an integer counter in the shared dictionary to make the read-modify-write sequence visible; it is not a complete authentication or production session implementation.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
- Validate the session identity and derive a stable dictionary key. Do not log the cookie or other secret session material.
- Create a lock object and acquire a lock for that session key. Use a new lock object for each simultaneous lock operation in separate Lua light threads.
- After acquiring the lock, read the current value, update it, and write it back. Re-reading after locking is essential: a request may have changed the state while this request was waiting.
- Release the lock promptly on success and every failure path. Do not continue with an update if acquisition timed out or failed.
-- /etc/nginx/lua/session_counter.lua
local resty_lock = require "resty.lock"
local sessions = ngx.shared.sessions
local sid = ngx.var.cookie_session_id
if not sid or not sid:match("^[%w_-]+$") then
ngx.status = ngx.HTTP_BAD_REQUEST
ngx.say("Invalid or missing session")
return
end
local key = "session:" .. sid
local lock, err = resty_lock:new("session_locks", {
timeout = 0.25,
exptime = 5,
})
if not lock then
ngx.log(ngx.ERR, "could not create session lock: ", err)
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("Session update unavailable")
return
end
local elapsed, lock_err = lock:lock(key)
if not elapsed then
if lock_err == "timeout" then
ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
ngx.header["Retry-After"] = "1"
ngx.say("Session is busy; retry the request")
else
ngx.log(ngx.ERR, "could not acquire session lock: ", lock_err)
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("Session update unavailable")
end
return
end
-- No yielding operations belong in this short critical section.
local count, get_err = sessions:get(key)
if get_err then
local _, unlock_err = lock:unlock()
if unlock_err then
ngx.log(ngx.ERR, "session lock unlock failed: ", unlock_err)
end
ngx.log(ngx.ERR, "could not read session state: ", get_err)
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("Session update unavailable")
return
end
count = (count or 0) + 1
local stored, set_err = sessions:set(key, count)
if not stored then
local _, unlock_err = lock:unlock()
if unlock_err then
ngx.log(ngx.ERR, "session lock unlock failed: ", unlock_err)
end
ngx.log(ngx.ERR, "could not store session state: ", set_err)
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("Session update unavailable")
return
end
local unlocked, unlock_err = lock:unlock()
if not unlocked then
-- The counter write has already succeeded. Do not imply that it was rolled back.
ngx.log(ngx.ERR, "session lock unlock failed after write: ", unlock_err)
end
ngx.header.content_type = "text/plain; charset=utf-8"
ngx.say(count)
The sample returns a deliberate service-unavailable response on lock timeout rather than proceeding as if it held the lock. The chosen timeout and expiry are examples only: keep the protected work short, give the expiry enough margin beyond its expected duration, and tune both from measurements. If a write succeeds but unlocking fails, the operation may already have committed; retries therefore need application-level handling appropriate to the operation.
Free tools Windows power users keep installed
One-click scans. No signup required.
Lock timeout, expiry, and supported phases
The lua-resty-lock documentation describes a shared-memory, nonblocking mutex that tries to lock a key across workers in the current Nginx server instance. Its documented defaults are a five-second wait timeout and a thirty-second lock-entry expiry; the timeout may not exceed the expiry. Those defaults are not a reason to leave locks held: call unlock() promptly, including on early returns. Expiry is a recovery backstop, not normal cleanup.
The library polls using cooperative sleeps rather than blocking an operating-system thread. Its documentation also warns that yielding APIs are not usable in every ngx_lua phase, including initialization, header/body filters, balancer, and log contexts. Put this logic in a supported request phase and verify the restriction for the deployed module version.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Choose the right mechanism for your deployment
One OpenResty instance with multiple workers
Use lua_shared_dict when workers on that instance need to see the same state. Use a lock around a per-session read-modify-write only when the update cannot be made atomic by another suitable operation. Protect the smallest possible section: acquire, re-read, update, write, release.
Multiple OpenResty instances or hosts
A shared dictionary and lua-resty-lock cover workers in the current server instance, not a fleet. If requests for one session can land on different hosts, use a shared external session backend or a coordination mechanism whose cross-instance behavior is explicitly designed for the requirement. Do not assume that a locally acquired lock protects a write performed on another host.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteLimiting traffic rather than protecting correctness
Use standard NGINX limit_conn or OpenResty’s resty.limit.conn when the policy is to cap simultaneous requests by an appropriate client or session key. These limiters address load admission. A per-session lock addresses conflicting updates. An application may need both, but a traffic cap is not a substitute for serializing a correctness-critical update.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Integrating a session library
The lua-resty-openidc package documentation notes a library-specific lifecycle detail: when server-side storage uses locking, the session returned from authenticate may still be locked, and its example closes that session explicitly. Check the behavior and required cleanup against the exact lua-resty-openidc version and storage backend in use rather than generalizing it to other session libraries.
Prevent cache stampedes with the same locking pattern
A cache fill is related to session locking but is not itself a session implementation. The lua-resty-lock documentation’s pattern is to check the cache, acquire a per-key lock after a miss, check the cache again, fetch only if it is still missing, write the result, and release promptly even when an error occurs. The second check avoids duplicating work when another request filled the cache while this request waited.
Troubleshoot common concurrency failures
- Two updates still overwrite each other: confirm both requests use the same stable session key, the state is actually shared, and every non-atomic read-modify-write path takes the lock. Re-read state after acquisition rather than using a value fetched before waiting.
- Workers see different values: check that the state is not in a Lua module variable or request-local value, and that every worker uses the same named shared dictionary on the same instance.
- Requests time out acquiring a lock: inspect critical-section duration and contention, ensure the lock is released on every path, and set a bounded wait policy with a deliberate response or retry behavior. Do not silently proceed without the lock.
- Lock creation or access errors: check that the named lock dictionary is declared in the
httpcontext, the module is installed and loaded, and the deployed API matches the example. Log errors without logging session secrets. - Shared-dictionary writes fail: check dictionary capacity and workload behavior. A configured size is not a guarantee that a particular session record will always fit; monitor the actual application and define what a failed write means.
- Behavior breaks after moving to more hosts: local dictionaries and locks do not coordinate across instances. Move state and coordination to a backend with the required cross-host semantics.
- A lock appears stuck after a worker failure: unlock promptly during normal control flow and configure a measured expiry as a recovery backstop. Do not rely on waiting for expiry during healthy requests.
- A limiter does not prevent inconsistent session state: verify whether the configured mechanism limits request admission or serializes the update. Use a session lock or atomic operation for correctness.
Or skip the browser setup
If your goal is a screenshot of a web page rather than managing its application session, ScreenshotNeo provides a website screenshot API and MCP server. This does not replace Nginx session storage or locking. One GET request can return an image or PDF; for example:
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for parameters. Before a capture, it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.
Further reading
- OpenResty Official Blog, “How to Share Data Between Requests in OpenResty,” updated July 7, 2026; and the
lua-nginx-moduledocumentation. - OpenResty Package Manager documentation for
lua-resty-lock,lua-resty-limit-traffic, andlua-resty-openidc. - OpenResty Official Blog, “How OpenResty and Nginx Shared Memory Zones Consume RAM,” updated July 7, 2026.
Frequently Asked Questions
Can a request acquire more than one lua-resty-lock lock at the same time?
Use a separate stateful lock object for each simultaneous lock operation running in different Lua light threads, and define a consistent acquisition order if an operation needs multiple keys.
Does a worker-local module variable become safe if requests use a lock?
A lock only coordinates code paths that participate in the same locking scheme. It does not turn separate worker-local module state into one shared value.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

