Setting up a WebSocket server for your Laravel app


This article has been cross-posted on the Knack Engineering blog.

Introduction

WebSockets are a ubiquitous tool for building real-time experiences for users. They provide a persistent, bidirectional connection between a client and a server. For example, say the frontend of your app needs to stay up-to-date within seconds of your backend to do things like deliver notifications, status updates, etc. You may have implemented this as a periodic check, or poll, of the backend via some API like REST or GraphQL. Now that you have more users, and/or your processes have become more complex, these requests can start to weigh on your infrastructure capacity. That’s a problem that WebSockets can help solve.

Laravel and its ecosystem play a significant role in our stack at Knack, and recently we embarked on a new WebSocket server implementation which would work closely with our Laravel-based core API. For the uninitiated, Laravel is a popular PHP framework and ecosystem that provides a rich set of tools and features for building modern web applications. We decided to use the swooletw/laravel-swoole library to build our server-side implementation of a custom subprotocol and I had the opportunity to document some of my experiences along the way. I’ll show how to get started with the library, provide some background information, some caveats to consider, and drop a few tips. Let’s get started!

WebSocket Server Solutions for Laravel

First, we are working with the assumption that you want, or need, to host your own WebSocket server, and that you want to do so in PHP. With a stateful protocol like WebSockets we need to be able to run PHP concurrently. There are basically two different approaches: language-level and extension-level.

Language-level libraries and frameworks implement concurrency in pure PHP. Examples include AMPHP and ReactPHP. In contrast, extensions are written in a lower-level language, typically C/C++, and expose APIs at the PHP-level to access the extension-level functionality. Swoole and OpenSwoole are examples of PHP extensions. In short, Swoole is an event-driven, asynchronous, multithreaded framework that makes it easy to build performant, concurrent servers.

Now let’s evaluate pre-packaged WebSocket Server solutions that easily plug into a Laravel app. On the language-level side we have the seemingly most popular choice: the beyondcode/laravel-websockets, a package by Beyond Code. It is built on Ratchet (which is built on ReactPHP), has a Pusher protocol implementation, and plugs well into the Laravel framework’s broadcasting API. While this supports a lot of use cases and does so in a familiar “Laravel way” it is not very flexible when you need something like a custom subprotocol implementation, and it is inherently limited in performance due to being built on a PHP server core rather than a C/C++ one.

Stargazer Statistics

On the extension-level side we have two libraries that are built around Swoole: swooletw/laravel-swoole and hhsxv5/laravel-s. They are both established packages with a wide contributor base, but my colleagues and I ultimately concluded that the sandbox and safety features within laravel-swoole were a bit more mature and reliable in our testing.

There are a few blog posts out there on getting started with laravel-s but not as many for laravel-swoole, so I felt particularly motivated to write and publish this article. The laravel-swoole default WebSocket implementation is built with Socket.io in mind, where laravel-s is a bit more agnostic in its implementation. Both packages have some feature overlap but some differences as well. I would consider both of them for your project and evaluate the best fit!

Getting started with swooletw/laravel-swoole

First, let’s install either Swoole or OpenSwoole. I’ll be using Swoole for this example. Be sure to enable support for WebSockets on installation when prompted like so:

Enable Sockets Support

pecl install swoole

If you run into any issues during the Swoole build process I included a few troubleshooting steps in the appendix.

Now, create a new Laravel app. Continue bootstrapping the app using Laravel Jetstream. I used the Intertia template, but I believe the API feature should work with Livewire as well.

laravel new
composer require laravel/jetstream
php artisan jetstream:install inertia

Let’s set up that feature: just enable it by uncommenting the line in config/jetstream.php:

'features' => [
    ...
    Features::api(),
    ...
],

Next, require the laravel-swoole package and publish its config files:

composer require swooletw/laravel-swoole
php artisan vendor:publish --tag=laravel-swoole

Here we’ll also want to adjust the config to enable the WebSocket server by default.

'websocket' => [
    'enabled' => env('SWOOLE_HTTP_WEBSOCKET', true),
],

Now, for this basic example we’ll just have our handlers defined inline as closures in the websockets “routes” definition. For anything that is more than a simple exploration I would recommend creating controllers or Laravel Actions to store the handler code.

<?php

declare(strict_types=1);

use App\Models\User;
use Laravel\Sanctum\PersonalAccessToken;
use SwooleTW\Http\Websocket\Facades\Websocket;

Websocket::on('whoami', function (SwooleTW\Http\Websocket\Websocket $websocket) {
    $websocket->emit(
        'message',
        $websocket->getUserId() === null
            ? 'You are not authenticated'
            : "Your userID is {$websocket->getUserId()}"
    );
});

Websocket::on('login', function (SwooleTW\Http\Websocket\Websocket $websocket, mixed $data) {
    if (is_string($data)) {
        $tokenInstance = PersonalAccessToken::findToken($data);

        if (
            $tokenInstance instanceof PersonalAccessToken &&
            $tokenInstance->tokenable instanceof User
        ) {
            $websocket->loginUsing($tokenInstance->tokenable);
            $websocket->emit('message', $tokenInstance);
        }
    }
});

Now we can test it out! Let’s start the Swoole server and test things out.

Note: You will need to disable Xdebug before you can run any Swoole code. If you skip this step your terminal will be overwhelmed with warning logs when you run this next command and things might not behave properly. If you expect to be doing a lot of Swoole development then you may want to configure a tool or script to enable or disable loading the Xdebug extension. For macOS there’s an open source tool to add a toggle button in the menu bar called xDebugToggler.

php artisan swoole:http start

Try navigating to http://127.0.0.1:1215 and seeing if you are able to register and login just like if you were to run php artisan serve. From there, head to the API Tokens section:

Jetstream API Tokens

Create a token and save it for the next step.

Create API Token

Now, let’s connect to the server via WebSocket and test our handlers! Open up your WebSocket client of choice. I’ll be using Postman here.

Let’s get connected and make sure everything works. Enter your hostname and port (likely 127.0.0.1:1215) and hit connect. You should see two messages come through and the status should still read CONNECTED.

Connect to WebSocket with Postman

If you’re wondering what those 1-2 digit numbers prefixing the server messages are, those are Socket.io packet type encodings. You can remove these and adjust anything about frame parsing by creating your own implementation of \SwooleTW\Http\Websocket\Parser.

Let’s send a whoami payload using this JSON:

[
  "whoami"
]

WebSocket whoami test

As expected we get the unauthenticated message. So let’s log in! Refer to the following JSON payload:

[
  "login",
  "YOUR_API_TOKEN"
]

WebSocket login test

And we get the $tokenInstance we emitted in our routes/websocket.php handler for login, and the default parser was nice enough to JSON-encode it for us! We can send another whoami to check our work:

WebSocket whoami second test

We now have a WebSocket server and a way to authenticate connections! This example is very basic, but I hope it gives a background to build something great with.

Appendix

Notes on using Swoole and laravel-swoole

Try Using Swoole (or RoadRunner) to serve your app

Swoole benchmark comparison

If you end up using a Swoole-based solution for your WebSocket server, why not serve HTTP requests using Swoole as well? Laravel’s request lifecycle by default is actually pretty redundant: for each incoming request that your Laravel app handles it needs to be fully bootstrapped every time: framework, service providers and all. There is a first-party solution to this: Laravel Octane, which uses your choice of Swoole (or OpenSwoole) or RoadRunner to provide a relatively easy way to serve many more requests by booting and loading the application into memory. Laravel Octane with RoadRunner is very likely to be a drop-in replacement for Nginx/PHP FPM for your Laravel app if you’d rather not add Swoole to your stack. Either way, it could be an easy win to dramatically increase your throughput for typical HTTP server needs using Laravel Octane, laravel-swoole, laravel-s, or another similar solution.

Choosing a WebSocket Room Driver

Be sure to choose your room driver, which associates WebSocket connections with users as well as membership in channels, appropriately for your use case. By default, the library will use a Swoole table to store these records. Swoole tables are an incredibly performant data store compared to Redis, as Cerwyn Cahyono concluded in May 2021. One consideration however is horizontal scaling: if you have more than one WebSocket server behind a load balancer, for instance, you need to consider that Swoole tables are only accessible by the Swoole server process and its forks.

If you need to have a common record among all of your WebSocket server instances with laravel-swoole then you may want to consider the provided Redis driver (\SwooleTW\Http\Websocket\Rooms\RedisRoom), or creating your own implementation. Be sure to add a prefix unique to the server for all records, that way you don’t end up sending a message intended for one WebSocket connection on Server A to another, unrelated WebSocket connection on Server B.

Implementing middleware for WebSocket frames/messages

You may also find that you’d like to have middleware for all incoming WebSocket messages. If all you need to do is interact with parts of the Frame then you can add this handling in a custom handler or parser. These are defined in config/swoole_websocket.php. If you need to get the user ID and interact with a WebSocket instead then you’ll have to override and extend the \SwooleTW\Http\Concerns\InteractsWithWebsocket trait to directly modify the Swoole onMessage handler.

Adding Swoole to an existing stack/system

If you have a system where a Swoole WebSocket server stands alongside other pieces like an HTTP server, queue worker, etc. then you will need to implement some kind of global pub/sub infrastructure that coordinates between the Swoole WebSocket server and everything else. Redis is one way to fill that need. You could have an async Redis client boot with the Swoole server and SUBSCRIBE to a given channel. The client could listen for a JSON payload which could simply have a user ID and data to emit to the authenticated WebSocket connection. That way, you could issue WebSocket messages from non-Swoole contexts by simply PUBLISHing the JSON payload to the corresponding channel. This does have the added overhead of having to establish a Redis connection for each emit from a non-Swoole context, but you get the flexibility of cooperating well with your existing system.

Troubleshooting installation of Swoole extension

When installing the Swoole extension on both ARM64 and x64 macOS machines I’ve run into a few issues and wanted to share how I resolved them.

fatal error: ‘pcre2.h’ file not found

If you get this error when installing Swoole then you need to be sure you have pcre2 installed. On macOS, you can do this using Brew:

brew install pcre2

Then you can use the Brew CLI to grep the location of the pcre2.h file and link it under your current PHP version’s include/php/ext/pcre/ directory.

brew list pcre2 | grep 'pcre2\.h$'

ln -s /opt/homebrew/Cellar/pcre2/xx.yy/include/pcre2.h /opt/homebrew/Cellar/php@x.y/x.y.z/include/php/ext/pcre/pcre2.h

fatal error: ‘openssl/ssl.h’ file not found

This guide doesn’t require building Swoole with OpenSSL support, but if you do you may need to set your OpenSSL directory during the build config. You can do so by first ensuring that you have OpenSSL installed locally, on macOS you can also do this using Brew:

brew install openssl

Then you can once again use the Brew CLI to get your OpenSSL directory and pass it in during the extension build configuration, right after executing pecl install. When prompted to enable OpenSSL support, type out “yes” and then add the --with-openssl-dir flag inline like so:

brew --prefix openssl
pecl install swoole


enable openssl support? [no] : yes --with-openssl-dir=/opt/homebrew/opt/openssl@3

Notes on WebSockets

Subprotocol gotcha

Be sure to pay attention to the Sec-WebSocket-Protocol HTTP header on the initial connection request. If the client request specifies a protocol in the header and the server doesn’t respond with that protocol, or any, then some browsers like Chrome will just drop the connection, which technically follows the WebSocket spec more closely, and others like Firefox and Safari will connect without hesitation.

Which WebSocket dev client to use?

For me this has been Firecamp, but I have gotten frustrated with the bugs and poor performance of the app. It has a lot of potential, so I’m definitely going to keep watching it! Insomnia just added WebSocket support, but it is still immature and lacking features. As of Jan 2023 I recommend using Postman, though note that even for them WebSockets support is somewhat of a beta.

Give your WebSocket server a heart(beat)

Be sure to implement some kind of heartbeat function for persistent WebSocket connections. It’s a good general practice, and helps when you have or want infrastructure configurations that close inactive connections. With many subprotocols the heartbeat is client-initiated.

Authentication Patterns

There are many patterns for authenticating WebSocket connections, but can be categorized as either during the initial connection request (authentication-on-connection) or afterwards within the established connection (authentication-after-connection). During the initial connection request the two most common approaches are to either use a cookie, or a token in the header or body. Typically, with the authentication-on-connection approach the connection is closed by the server if the authentication check fails. With the authentication-after-connection approach typically servers have a timeout which closes connections that don’t authenticate within a given timeout. At Knack, we created a WebSocket backend that implemented the graphql-transport-ws subprotocol which frontend library enisdenjo/graphql-ws supports.

For reference, laravel-swoole is configured by default for authentication and other middleware to be run on the initial connection request. While this is a valid approach, my impression is that the dominant WebSocket authentication pattern is to support authentication-after-connection. For this guide I implemented an authentication-after-connection flow as a barebones custom subprotocol. Before proceeding with your project be sure to consider what kinds of clients will be connecting to your WebSocket server and choose your approach accordingly.

Laravel News Links

Laravel create/show Route Doesn’t Work? A Typical Mistake.

https://laraveldaily.com/storage/322/Wrong-Way.png

If you have a few similar GET routes, there’s a danger of one overriding another.

Example 1: Two GET Routes

routes/web.php:

Route::get('posts/{post}', [PostController::class, 'show']);

Route::get('posts/create', [PostController::class, 'create']);

The problem with this pair is that “create” will match the same way as {post}, so if you load /posts/create in the browser, it will execute the first route of /posts/{post}, assigning {post} == "create".

In that case, you need to change the order:

routes/web.php:

Route::get('posts/create', [PostController::class, 'create']);

Route::get('posts/{post}', [PostController::class, 'show']);

Then, both routes would start working.


Example 2: Resource Controller with Extra Method

routes/web.php:

Route::resource('posts', PostController::class);

Route::get('posts/export', [PostController::class, 'export']);

If you launch /posts/export in the browser, it will instead execute the show() method of the Controller, and not the export() method.

The reason: as a part of Resource Controller, there’s a show() method, which has a signature of posts/{post}. So it will match the same way as posts/export.

If you want to add extra methods to Resource Controller, you need to add them before the Route::resource():

routes/web.php:

Route::get('posts/export', [PostController::class, 'export']);

Route::resource('posts', PostController::class);

The general rule of thumb is to have specific no-parameter routes earlier in the Routes file than the “wildcard” routes with parameters.

Laravel News Links

7 Practical GitHub Repositories That Will Teach You Python

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/02/hand-holding-python-logo.jpg

Recent innovations in Artificial intelligence have catapulted Python’s popularity. People marvel at what AI can do, and the productivity benefits machine learning is bringing to the tech world.

Python programming powers many global industries, including data science, web development, finance, and security. It’s gradually becoming a sought-after tech skill.

There are many resources available online to learn Python programming. But not all are practical. These GitHub repositories all feature practical tutorials to boost your skills.

This repository lists programming tutorials for various languages, including Python. It has contributions from over 100 experienced software developers. As a learner, you will practice with tutorials and learn how to build applications from scratch.

The tutorials include various projects that allow a learner to practice Python-based skills. These include machine learning, web scraping and building bots, and web applications. You get to work on real-world projects and gain in-demand skills.

The tutorials use a combination of programming languages to create the projects. You, therefore, get to work with other languages and technologies alongside Python. So while learning Python, you get acquainted with other languages and communities.

This repository is the go-to place for Python Algorithms. Mastering essential algorithms is a skill every programmer should have. It contains many algorithms implemented in Python. The repo is an open-source community of programmers building new projects. They help each other with ideas and problem-solving. Their main goal is to work together to document and model helpful algorithms using code.

When you join the community, you practice and contribute to existing projects. They have social media accounts where developers communicate, debug and discuss projects.

The community keeps you updated with the latest Python programming news and guidelines. They also have repositories and communities of other modern programming languages.

A seasoned Python programmer named Asabeneh Yetayeh created this repository. It’s one of the many repositories he created for modern programming languages.

30 days of Python programming is a challenge for beginners to learn Python in 30 days. It’s a step-by-step guide that includes everyday challenges. As a learner, you have notes and exercises to test your learning at the end of each lesson. The exercises have categories 1-3 to test your understanding of the day’s concepts.

To earn a certificate, you must actively engage in the 30DaysOfPython challenge. There is a telegram group for anyone interested in the 30-day sprint. When you complete the challenge, you will earn a certificate. You also have the choice to learn the course at your own pace and take longer than the 30 days challenge.

As a learner, you can raise issues and contribute to the repo. The course has a star rating of 18000-star rating of GitHub, so it would be worthwhile to check it out.

This is a practical machine learning course by Siraj Vajal. It’s a 100-day challenge for machine learning enthusiasts. Siraj segments the course into notes and daily activities. This schedule exposes you to machine-learning concepts gradually.

You’ll start with introductory guides which cover topics like installation of the necessary Python tools and software. Later, you’ll advance to more complex concepts like decision trees and logistic regression. The guide provides the needed datasets and code you can use during practice.

Machine learning is a complex topic that you may find it daunting. This course teaches you the fundamentals at a slow enough pace to remain manageable.

This is a Python playground created by Oleksii Trekhleb and other contributors. It provides an interactive interface for you to change and add code to see how it works.

The repository encourages you to practice Python programming using the following steps:

  1. Pick a topic you would like to learn or recap.
  2. Read the instructions linked on the docstrings in the scripts.
  3. Examine examples of code and assertions to see the expected output.
  4. Change assertions, add and run the code to practice.
  5. Run tests to see if it works correctly.

You can check your code against the provided Python code style guides. This helps to learn Python syntax and expressions through practice. It also improves the quality of your code. You can use the repo as a cheat sheet to recap statements and Python constructions.

This course by David Beazily covers the foundational aspects of Python programming. It emphasizes script writing, data manipulation, and organization of programs. The course is not for absolute beginners in programming. It targets developers with experience in other programming languages other than Python.

This course is part of David’s instructor-led courses. He uses the same course in Python for corporate training and professional development. As a learner, you will be learning and practicing on real-world projects.

The course helps you understand and work better with complex Python programs. You learn to write quality and modify or read code from other developers. It includes 25-35 hours of intense work, including hands-on coding exercises. But you also have the option to learn at your own pace.

Jeffery Hu created this repository for Python challenges. The repo includes 100+ Python exercises for users to test their programming skills. The exercises include exciting projects like creating games, translation programs, and manipulating features.

The repository includes accompanying notes that explain requirements and expectations. You can practice with these examples using the online IDE that runs in a browser. Jeffrey set up the IDE for beginners struggling to set up a local environment. It helps you to learn the language by practicing it as you read.

Why Learn Python?

Many developers regard Python as a beginner-friendly language. Its accessible syntax and efficient language structures bring a productivity boost. Python is versatile, making it useful in creating real-life solutions. You can use it in simple projects and complex projects like AI development.

Python improves with each release. The latest version, Python 3.11, has many improvements. There are new library modules and improved interpreters, among other enhancements. These improvements make writing code, debugging, and setting up projects easier.

MakeUseOf

‘Legend of Zelda: A Link to the Past’ Reverse-Engineered for Linux, Switch, Mac, and Windows

More than 30 years ago Nintendo released the third game in its Legend of Zelda series — appropriately titled, "A Link to the Past." This week Neowin called it "one of the most beloved video games of all time," reporting that it’s now been reverse-engineered by a GitHub user named Snesrev, "opening up the possibility of Link to the Past on other platforms, like Sega’s 32X or the Sony Playstation."
This reimplementation of Link to the Past is written in C and contains an astonishing 80,000 lines of code. This version is also content complete, with all the same levels, enemies, and puzzles that fans of the original game will remember. In its current state, the game requires the PPU and DSP libraries from LakeSNES, a fast SNES emulator with a number of speed optimizations that make the game run faster and smoother than ever before. Breaking from the LakeSNES dependency, which allows for compatibility on modern operating systems, would allow the code to be built for retro hardware. It also offers one of the craziest features I have seen in a long time; the game can run the original machine code alongside the reverse-engineered C implementation. This works by creating a save-state on both versions of the game after every frame of gameplay, comparing their state and proving that the reimplementation works…. Snesrev now works alongside 19 other contributors. Despite the immense amount of work that went into this project, the result is brilliant. Not only does the game play just like the original, it also includes a number of new features that were not present in the original. For example, the game now supports pixel shaders, which allow for even more stunning visuals. It also supports widescreen aspect-ratios, giving players a wider field of view, making the game even more immersive on modern displays. Another new feature of this reimplementation is the higher quality world map. The new map is much more detailed and gives players a better sense of the world they are exploring…. The amount of time, effort, and talent that went into creating this is simply astonishing. Thanks to Slashdot reader segaboy81 for sharing the article.


Read more of this story at Slashdot.

Slashdot

Stockpiling SHTF Ammo – How To and How Much?

https://www.alloutdoor.com/wp-content/uploads/2023/01/m2-military-surplus-ammo-storage-container.jpg

Armed preppers were once derided as paranoid hoarders. Then, COVID happened. We saw empty shelves in grocery stores, lack of access to medications for chronic conditions, and mass civil unrest exacerbated by unemployment and politicking. In short, the pandemic gave us a taste of a real “SHTF” scenario. When it comes to preparing for natural or man-made disasters (or another end-of-days global infection), you need to invest in five things: food, water, shelter, power, and personal defense. That last one means having a stockpile of ammunition to feed your pistols, shotguns, and long rifles. Let’s dive into how to properly store SHTF ammo for the long haul, and take a look at how much you might want to keep around, just in case.

How to Store Ammo Long-Term

Three things determine whether ammo – once pulled out of storage after years – fires reliably, or fizzes out: Temperature, exposure, and moisture.

Ideal Temperature for Ammo Storage

Regardless of the caliber, casing, or powder, all ammo should be stored at 55 to 80 degrees (F). Colder temperatures can cause the sealant on primers to fail, and condensation can more easily form. The inverse is also true: Very high temperatures can exacerbate the effects of humidity and lead to rapid corrosion. Even in dry cold or heat, extreme temperatures can cause gunpowder to break down, resulting in misfires and unreliable cycling.

Keeping Ammo Dry

SHTF Ammo

Two words: Desiccant packs. You probably know these as “dehumidifiers.” If you’ve ever found a small, cloth packet of plastic beads inside some packaging, you’ve seen a desiccant pack. These little perforated pouches contain silica gel beads, which absorb moisture in the air. They’re excellent at preventing a container of ammo from accumulating moisture. It’s best to invest in properly sealed containers for your ammo. That means something made of decent polymer or coated steel, with a rubber gasket providing a proper seal. We can recommend a few cases to keep things simple.

The Best Ammo Storage Containers

US Surplus M2 Ammo Can

SHTF Ammo

The M2 Ammo Can is arguably the best ammo storage container available. It’s made from steel, it’s coated with a rustproof paint, it’s easy to carry, it can hold plenty of weight (up to 50 lbs.) and it has a reliable gasket seal with a sturdy clamp.

MTM .50-Cal Polymer Ammo Can

SHTF Ammo

The MTM Ammo Can is basically a polymer version of the M2. It’s similar in size, and it features a rubber gasket seal with a decent clamping lid, carry handle, and padlock holes for basic security. Plus, MTM containers are made in the USA.

Pelican 1200 Case

SHTF Ammo

The Pelican 1200 Case provides plenty of space for stacked rifle or pistol magazines, and its legendary toughness and pressure-equalizing seal make it a great choice for long-term ammo storage. This writer employs a few 1200s as his choice for ammo storage, having “tactically acquired” a few from his unit’s armory in prior years. Keep your ammo stored in any of these sealed cases with some dehumidifying packs, and it’s guaranteed to remain stable and ready for use for years, if not decades.

The Best Places to Store Ammo

First, let’s clear up where you shouldn’t store ammo. You should avoid any location wherein your ammo containers are subjected to wild temperature swings. That means no attics, sheds or garages. Basements without insulation or climate control should also be avoided. Besides temperature concerns, these three locations should be avoided for security reasons. Most burglars attempt to forcibly enter a home through the garage or basement, and auxiliary buildings are easier targets since they’re physically separate from the main property.

Indoors, Away From Sunlight

Spare closets, empty spaces under bed frames, and unused kitchen cabinets make great spots. These places provide stable temperatures, they’re easily accessible, and they’re not in vulnerable locations.

Keep It Locked Up

Locking ammo is as important as locking up your guns. Keeping ammo indoors means curious children or wayward guests can stumble upon your rounds. Discourage prying eyes and small digits by slapping some locks on your ammo containers (all the containers we recommend can be secured with padlocks).

How Much Ammo Should I Stockpile?

You can never have too much — as long as it’s stored correctly, that is. You should consider the minimum amount of rounds that’ll make you feel secure for the long haul in a true “SHTF” scenario. If Earth were hit by an X-class solar flare and civilization was sent back to the Stone Age, this writer would want enough ammo on tap to last the rest of his (probably shortened) life. So, how much ammo would one need to last, say, 20 to 40 years in a potentially high-conflict environment? We can answer this question – at least, we can ballpark it – with some real data.

Handgun Rounds Stockpile

SHTF Ammo

Data collected from law enforcement shootings with handguns reveal that, on average, it takes 13 to 14 rounds to incapacitate a single threat. In a “SHTF” scenario, you’d want to avoid the public and venturing beyond your safety zone as much as possible. But war-game the idea that you’d need expose yourself at least a few times a month: Assuming you’re in a high-threat environment, you’d want enough ammo to protect yourself from multiple threats. Given the assumption you’re in this doomsday situation for the long haul, some napkin math says you’d want over 1,000 rounds.

That’s about 20 boxes of ammo (most pistol cartridges come in packs of 50). That amount of rounds can be easily stored in a single large container like the Pelican 1200. That’s also enough ammo to hone your marksmanship skills on a regular schedule, while still keeping more mags than you could ever hold ready to go.

Rifle Rounds Stockpile

SHTF Ammo

If you’re like most preppers or survivalists, your mind automatically jumps to 5.56 NATO/.223 Remington, chambered in an AR-type rifle. Speaking from personal experience, it’s surprisingly easy to burn through 210 rounds (that’s seven 30-round magazines, the standard “battle rattle” load) when you’re in a real threat engagement.

You’d want at least enough ammo to replenish those seven mags through multiple threat encounters. Again, if we’re considering the potential for years-long conflict and severe social strife, it’s safe to say that harboring at least 2,100 rounds of rifle ammo is a safe minimum. Stored in typical 20-round boxes, this amount of rounds can comfortably fit in two .50-cal ammo cans.

Hunting Rounds Stockpile

SHTF Ammo

Preppers lucky enough to survive on game in rural areas, rejoice. You probably need many fewer rounds to live comfortably, but you should still keep more ammo than you need for that trusty bolt gun. Data says that the average hunter expends between 3 and 7 rounds to take one deer. Assuming you’re living off game meat, you’ll want to take at least a few bucks or does to keep the fridge or salt locker stored. It’s safe to say that you’ll want at least 500 to 800 rounds of hunting ammo. Speaking of hunting: having reliable ammo and an accurate rifle is just part of the equation. See our top tactics for ensuring a successful hunt when survival is on the line.

The post Stockpiling SHTF Ammo – How To and How Much? appeared first on AllOutdoor.com.

AllOutdoor.com