zpool txg_sync

Tuning needed for zfs parameters or server vm

How to tune zfs or system itself so that txg_sync is not in uninterrupted sleep state ?  ubuntu server 16.04 (kernel 4.15)installed on ZFS backed(no ext4 or xfs), below is zpool status. the server has [256 GB of memory and 46 core cpu] and HDD is 10K SAS drives(no SSD disk). the pool "root_pool" is created with below options enabledashift=12, atime=off , canmount=off ,compression=lz4,logbias=throughput,sync=disabled and No deduplication is enabled (zfs get all output in end)
zpool status 
  pool: root_pool
 state: ONLINE
  scan: none requested
config:
NAME        STATE     READ WRITE CKSUM
root_pool     ONLINE       0     0     0
  sda2      ONLINE       0     0     0
errors: No known data errors
  pool: PoolB
 state: ONLINE
  scan: none requested
config:
NAME        STATE     READ WRITE CKSUM
PoolB  ONLINE       0     0     0
  sdb       ONLINE       0     0     0
errors: No known data errors
# lsblk
NAME  MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sdb 8:16  0 1T 0 disk 
├─sdb9  8:25  0 8M 0 part 
└─sdb1  8:17  0 1024G 0 part 
zd0 230:0 0 4G 0 disk 
sda 8:0 0 1T 0 disk 
├─sda2  8:2 0 1024G 0 part 
├─sda9  8:9 0 8M 0 part 
└─sda1  8:1 0 1007K 0 part 
below is a snippet of the output of iostat -x  where the %iowait value is constantly 5% to 13%
when i search for the process in interruptible sleep
S   PID CMD
D  5858 [txg_sync]
D  4356 [txg_sync]
above is process name I see 99% of the time and the pid 4356 doesn't change
Below is output of zfs getall root_pool/logs which is more io intensive
NAME     PROPERTY              VALUE                  SOURCE
root_pool  type                  filesystem             -
root_pool  creation              Wed Nov 28  8:06 2018  -
root_pool  used                  621G                   -
root_pool  available             363G                   -
root_pool  referenced            96K                    -
root_pool  compressratio         3.62x                  -
root_pool  mounted               no                     -
root_pool  quota                 none                   defau        
sda is maxed out at %util 100. And it's a single-disk pool, so that doesn't likely mean sda is failing, it just means you're asking it to do more than a single disk can do.
Tuning isn't going to fix this, you just plain need more IOPS. Your options are 1. add more vdevs to the pool or 2. replace sda with an SSD.
In general, the IOPS profile of a pool is additive of all vdevs. So you have a single vdev (whether it's one disk, or a six-disk stripe) you get one disk's worth of IOPS. You add a second vdev (again, whether single disk, or n-wide stripe) and you get another disk's worth of IOPS. This is a general trend, not a hard-and-fast exact measurement, but it's good enough for calculations.
You'll be able to roughly double the performance you're seeing now if you add another vdev to the root pool. Of course, you'll also be roughly doubling the likelihood of a failure than can bring the pool low, since you're rocking single-disk vdevs, and therefore have no parity or redundancy. Whether this is acceptable or not is up to you, but be certain you've thought through the consequences of a catastrophic pool failure.
A single decent SSD will give you three orders of magnitude more IOPS than that 10K SAS disk you're using right now. The kicker is going to be the cost per TB of storage. If you're storing a lot of data, you might need to just add more spindles instead. If you do add more vdevs, you're going to need to balance the data you've already got; this ideally would mean backing data up externally, destroying the pool, then copying the data back on board after adding the new vdevs. You canjust add the vdevs, backup the data, then delete the data (and all snapshots containing it) then copy it back on the expanded pool... but it's cleaner to just destroy it.
If you switch from single disk vdevs to mirrors, you get more options. Each vdev still only gives you a single disk worth of write IOPS, but it gives you two disks' worth of read IOPS - probably not critical for a log server - and it gives you the ability to rebalance data on-the-fly with a small risk window:
  • scrub the pool (do not skip this initial step!)
  • detach one disk from each mirror
  • create a new pool with the detached disks, and any new disks you're adding
  • replicate from old pool to new
  • quiesce any write sources
  • replicate from old to new again (will go extremely rapidly; typically <1 min)
  • destroy old pool
  • export new pool, reimport new pool with old pool's name
  • attach remaining disks from destroyed pool to disks in new pool to upgrade from single-disk vdevs to mirror vdevs again
  • de-quiesce data sources
https://www.reddit.com/r/zfs/comments/7l64mt/what_zol_performance_optimization_settings_do_you/

zfs without slog ?

Sync=disabled will indeed improve write performance, but at the cost of possibly losing data if your server crashes or loses power after a write.
I run my personal servers with sync=disabled because that's an acceptable risk to me. However, it won't be to everyone.
One case where sync=disabled is perfectly fine is when initially copying a large amount of data to the ZFS filesystem. You'll know for sure if the server crashed or shutdown during the copy, so you can leave sync disabled until the copy is complete.
One case where it's not okay is a large file server serving multiple users. If the server crashes right after a user thought he saved his file successfully, then the user finds out it didn't save, you will have an angry user on your hands.


  1. Sync writes go to in-pool ZIL (slow), async writes go to RAM
  2. See 1
  3. sync=disabled will mean that your sync writes are no longer synchronously written to disk; this opens you up to the possibility of data loss on these filesystems if there is a crash. logbias=throughput means the writes would have lower priority in the ZIL.

My sytstem has 2 pools:

1 is a data (non-bootable) 10-disk raidz2 pool that has a SLOG already (2 mirrored partitions from a pair of m.2 intel optane drives)

the other pool is a single nvme drive (970 pro) that holds the system's root filesystem. This is mainly using zfs (vs ext4/xfrs/btrfs) to allow sending/receiving snaphots from the raidz2 pool, so i can have a whole bunch of them that can all be used to restore the system without taking up space on the nvme ssd.

This is ZoL (OS is Fedora 29). so not a whole lot of sync writes by default.

Currently I have sync=standard on both, logbias=throughput on the nvme root pool, and the raiudz2 pool uses logbias=latency

Im fairly sure the raidz2 pool it set right, but with the root drive i really am not sure, and dont eve know if zfs uses the same behavior as with a pool, since any "fake-slog" writesto the drive would seeingly just be writing data to the drive normally, whereas with a pool i believe these will get directly written (not as a raidz striped write) which avoids the extra I/O that using parity adds.

I also could add another partition to the intel drives and use those as a mirrored (or striped) SLOG. nvme drive has higher max throughput, but not necessairy at low queue depths. THe optane drives also have a few other nice properties from a "preventing data loss" viewpoint (can be mirrored, use direct writing not a volatile flash cache, etc)


ChrisOfAllTrades

If sync writes are that light against the RAIDZ2 pool, I'd wonder if you really need the SLOG at all. If it's media storage and stuff where latency really doesn't matter, you could just remove it and see if there's a major impact.

As far as the root pool, the same comment I made above about the "double writes" when using in-pool ZIL apply, but if your sync writes are minimal (just running a regular OS on top of it) then I wouldn't be terribly concerned. It's more of an issue if you're using it to host VM images where lack of sync writes can cause corruption.


Oh i know it doesnt have a very big impact. My reasons for implementing it were more-or-less:
  1. it will help a little with synced writes. Even if there arent many, there are a non-zero number of them occurring.
  2. I saw some reports tat not having a SLOG could lead to pol fragmentation over time (or at least speed up how quick fragmentation occurs by a little bit)
  3. the 2x 32gb optanes set me back something like $110 bucks. Of those 64 gb, 8 gb (4 from each drive)is dedicated to the slog (mirrored, so 4 gb usable), and the other 28 gb on each driveis use is used for dual swap devices (which I neded/wanted anyways). So were talking about a $15 or so investment.
The 10x 8gb toshiba N300 drives and 1tb 970 pro set me back nearly 3 grand. So, basically if it improves things half a percent im getting my money's worth out of it.
that said, i still wasnt to set things up optimally, even if it isnt a huge difference in real-world performance.
the same comment I made above about the "double writes" when using in-pool ZIL apply,
Even with a 1-disk pool? i mean i get why youd have this in a raidz setup - you can setup the on-pool ZIL as striped (for speed) and/or mirrored (for redundancy) and avoid the I/O penalty associated with parity.
... But on a single disk, it seems like (unless im misunderstanding something) there would be literally 0 benefit by doing this over just prioritizing the sync writes, since writing to a ondisk zil wont register the writes as completed any faster than "just writing them first" but will still require re-writing them.
side question: say i partitioned off another few gb from the optane drives and made a slog for the nvme drive. Assuming a relatively small number of sync write (i,e., non-database workload), would this ever hurt the overall speed/throughput/data integrity of the root pool? (assume that there are few enough sync writes that the optane drives never hit 100% I/O capacity within a given 5 second write window).
As long as this wont hurt and might help a little i mine as well, for the same reasons i implemented it on the raidz2 pool.

Lack of SLOG + sync writes will indeed increase fragmentation due to the double writes.
Good use of the spare space on the Optane drives as swap (which you hope to tune your system never to use anyways, I assume)
Even with a 1-disk pool? i mean i get why youd have this in a raidz setup - you can setup the on-pool ZIL as striped (for speed) and/or mirrored (for redundancy) and avoid the I/O penalty associated with parity.
In-pool ZIL can't be configured, it's just "there" - you can configure your SLOG vdev(s) however you like of course, but mirrors are recommended. And yes, even on a single-disk stripe, you have an in-pool ZIL.
... But on a single disk, it seems like (unless im misunderstanding something) there would be literally 0 benefit by doing this over just prioritizing the sync writes, since writing to a ondisk zil wont register the writes as completed any faster than "just writing them first" but will still require re-writing them.
Blame the atomic nature of ZFS for this one. It still needs to order things into transaction groups (txg's) and then commit those as an unit that either succeeds or fails as a whole.
side question: say i partitioned off another few gb from the optane drives and made a slog for the nvme drive. Assuming a relatively small number of sync write (i,e., non-database workload), would this ever hurt the overall speed/throughput/data integrity of the root pool? (assume that there are few enough sync writes that the optane drives never hit 100% I/O capacity within a given 5 second write window).
Should work. Optane by design is direct-to-NAND write so you won't have to worry about competing cache flushes, and as long as you don't exceed the total bandwidth available to the underlying device it shouldn't choke the main 10-drive pool.
If we had better access to NVMe devices that supported multiple namespaces and QoS, you could actually enforce that at the hardware level. But I haven't found anything readily consumer-available with that.

##
Student
Good use of the spare space on the Optane drives as swap (which you hope to tune your system never to use anyways, I assume)
in my case its not really a matter of tuning. The system is intended for (among other things) data processing work. It has an i9-7940x that ie already maxced out with 128 gigs of fairly fast (3264 mhz 14-14-14-34) ddr4, and, well, thats just not enough.
Unfortunately, to get more from intel you have to go xeon which is a major cost hike, and going amd id lose significant performance since i can utalize avx512. plus ddr4 is stupid expensive right now.
Im hoping in the not too distant future optane + some software optimization will allow you to basically use optane drives like you would ram and use ram as effectively a L4 CPU cache. Itll never be as fdast as ram, but it doesnt need to be, it just needs to be fast enough to make sure the ram has the stuff the L3 cache is going to ask for in memory before it asks for it. And it seems like this use case is something intel is actively working on (and which would significantly increase the number of potential buyers who can actually benfit from optane), so i think it has a decent shot of actually happening
Anyways, im getting off topic.
(side note: im also rather fond of zfs since its basically the only thing i use other than MKL that utalizes avx512)
Blame the atomic nature of ZFS for this one. It still needs to order things into transaction groups (txg's) and then commit those as an unit that either succeeds or fails as a whole.
ahh, ok that sort of makes sense. Plus i resize that zfs isnt really designed with single drive pools in mind (if it were i imagine they wouldnt have labeled them as "drive pools" lol).
Should work. Optane by design is direct-to-NAND write so you won't have to worry about competing cache flushes,
this is one of the reasons I specifically got optane (vs a standard nvme) to do double duty as slog and swap. between this, low queue depth performance, and high durability, its almost like optane was designed specifically to excel as an slog / in other slog-like use cases.
Should work. Optane by design is direct-to-NAND write so you won't have to worry about competing cache flushes,
appreciate the confirmation. I cant see this ever happening unless my system, usage drastically changes. The little optane drives dont have the performance of their big brothers (like the 900p), but its performance is more than enough for the sync writes my system currently does. (performance is surprising good considering the price - id probably argue it is literally the best SLOG you can get on the planet for $20 or less, lol)

##
If you don't have an SLOG device, in-pool ZIL is extra-slow because you're writing first to the ZIL for safety, and then having to write again to the pool itself.
If you don't mind the risk of data loss to in-flight data, go ahead and set sync=disabled but do backups to other media if you value anything there.
In above quote, do you mean logbias=throughput will directly write the sync writes to the pool
As I understand it, sync writes will still hit the ZIL, but writes from datasets with logbias=latency will be serviced first, in sort of a "pre-emptive" way.
Since i dont have fast SSD for ZIL i think the disk-ZIL is use less any way
It's still going to provide safe write capacity for sync writes, it's just going to enact a significant toll on your performance while doing it.
Is there any way i can determine if the writes are sync or async or ratio of sync/async writes ?
I'm not sure if Richard Elling's zilstat script is provided with the default Ubuntu ZFS installation, but if not, you can get it from here:
I admit I haven't tried too much with ZoL.





Is there any performance impact due to different sized vdev's in a single pool ?

Is there any performance impact due to different sized vdev's in a single pool ?

I have existing pool eg. MyPool with 1 raidz vdev(3 x 500GB, 15000 rpm) and its almost 80% full. Now i want to add
5 X 1TB (15000rpm) disks on a raidz1 configuration to MyPool. But on doing so i get below warning
mismatched replication level: pool uses 3-way raidz and new vdev uses 5-way raidz
im concerned with
  1. What would be the total usable storage space i get from the newly added vdev with 1 TB disks(i assume it to be 5-1=4TB ) will it be 4TB or 1TB(same as existing raidz vdev 3-1=two 500GB disks=1TB )
  2. Are there any impact if i forcefully add them ignoring above message ?Yes, there's a performance impact. It may or may not be critical for you, and it will usually still mean better performance than having one vdev fewer in your pool.
    Let's say you have a pool with one 1T vdev. This pool, regardless of the type of vdev, will approximate the IOPS of a single disk under heavy load. (Exception: a mirror vdev will follow this rule for writes, but read IOPS will approximate the read IOPS of the total number of disks in the mirror vdev.)
    Now, let's say you have a pool with two 1T vdevs. Being of equal size, the pool will generally allocate writes evenly between the two vdevs. This pool has IOPS approximating the IOPS of two disks when under heavy load.
    Now, let's say you have a pool with one 1T vdev and one 2T vdev. The pool will generally distributes writes such that the vdevs fill up at an even rate, meaning double the writes to the 2T vdev that the 1T vdev experiences. This pool will most frequently approximate the IOPS of 1.5 disks when under heavy load - a full disk's worth of IOPS for the 2T vdev, and half a disk's worth of IOPS for the 1T vdev, which will tend to spend half its time binding on waiting for the 2T vdev to finish its crap.
    Of course, this all assumes that the pool and its vdevs are empty at the start: if you have, instead, a half-full 2T vdev and you add a new, empty 2T vdev, then even though the vdevs are the same size, you'll still approximate 1.5 disks worth of IOPS for the pool, because ZFS will still write twice as many records to the empty 2T vdev as to the already-half-full vdev, so that they'll fill up at the same rate and become full at the same time.
    It's also worth noting that reads of things already written solely to the first vdev will still come solely from that vdev, which will impact the IOPS profile of your system according to how many reads are from distributed data vs from the original data which was only one the original vdevs.
    Whew. Still with me so far?
    At the end of the day, adding the new vdev is unlikely to make your performance worse than it was before adding the new vdev - and if you're starting out with a ton of data already on one vdev with no plans to rebalance it, it probably won't be any worse than it would've been if you added a matching vdev, either.
does adding new raidz vdev with 5x 1TB disks to existing raidz vdev (3x500GB) give me additonal 4TB

Yes, roughly speaking. The size of your existing pool has no impact on how much usable space is on the new vdev; all usable space in the new vdev becomes usable space in the pool itself, no matter what.
"4T" is only roughly accurate, though. A RAIDz vdev approximates the amount of space of n-y disks, where n is the total number of disks in the vdev and y is the parity level. But it's only an approximation; you can consult an online storage calculator for a much closer estimate.

ubuntu 16.04 syslog over TLS

main server(Receiver - rsyslog.Master.local) - 10.45.9.201

client(Sends log to main server) - 10.45.9.173

## To verify particular CA cert have signed specific SSL crt

cd /opt/immune/etc/remote_connection/certificates
# openssl verify -verbose -CAfile ca.crt ssl.crt
ssl.crt: OK

# MAIN server receiver
1) We will begin by creating a new self-signed CA certificate. As of this post, the requirement for new SSL is 2048bit. Anything 1024bit or less is considered to be obsolete. Once you run the second command, you will be prompted for some basic information about your company.

openssl genrsa 2048 > ca-key.pem
openssl req -new -x509 -nodes -days 3600 -key ca-key.pem -out ca-cert.pem

2) Next, we will create a sets of keys. This is done in three steps. First we create the request, remove the password, then sign it with our CA certificate from step 1.

openssl req -newkey rsa:2048 -days 3600 -nodes -keyout server-key.pem -out server-req.pem
openssl rsa -in server-key.pem -out server-key.pem
openssl x509 -req -in server-req.pem -days 3600 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem

3) Copy all pem files to /etc/ssl/certs

4) Open the rsyslog configuration and add in the lines below. Order is important.

$DefaultNetstreamDriver gtls
$DefaultNetstreamDriverCAFile /etc/ssl/certs/ca-cert.pem
$DefaultNetstreamDriverCertFile /etc/ssl/certs/server-cert.pem
$DefaultNetstreamDriverKeyFile /etc/ssl/certs/server-key.pem

$ModLoad imtcp

$InputTCPServerStreamDriverMode 1
$InputTCPServerStreamDriverAuthMode anon
$InputTCPServerRun 5822 ## syslog tls listens on TCP port 5822

service rsyslog restart

## CLIENT server

1) Upload the ca-cert.pem file only to the /etc/ssl/certs directory on each client.

2) You will need to make sure the rsyslog-gnutls package is installed in order to use TLS

apt-get install rsyslog-gnutls

3) Edit the /etc/rsyslog.conf configuration file and add the following lines at end of file

## syslog over ssl

$DefaultNetstreamDriverCAFile /etc/ssl/certs/ca-cert.pem
$DefaultNetstreamDriver gtls
$ActionSendStreamDriverMode 1
$ActionSendStreamDriverAuthMode anon
#*.* @@(o)server.example.net:10514 # send (all) messages
*.* @@10.45.9.201:5822


reference: https://www.rsyslog.com/doc/v8-stable/tutorials/tls.html
https://linux.die.net/man/5/rsyslog.conf


zfs tune article

https://docs.oracle.com/cd/E53394_01/html/E54801/zfspools-4.html

http://open-zfs.org/wiki/Performance_tuning

https://pthree.org/2012/12/13/zfs-administration-part-viii-zpool-best-practices-and-caveats/

http://jrs-s.net/2015/02/06/zfs-you-should-use-mirror-vdevs-not-raidz/


parted partition alignment

I just tested in a vm with centos 6.7:
# parted /dev/sdb 
GNU Parted 2.1
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print
Error: /dev/sdb: unrecognised disk label                                  
(parted) mklabel gpt                                                      
(parted) mkpart primary 1m 100%
(parted) quit                                                             
Information: You may need to update /etc/fstab.                           

[root@localhost ~]# parted /dev/sdb print 
Model: VMware Virtual disk (scsi)
Disk /dev/sdb: 1074MB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start   End     Size    File system  Name     Flags
 1      1049kB  1073MB  1072MB               primary

[root@localhost ~]# parted /dev/sdb "unit s print"
Model: VMware Virtual disk (scsi)
Disk /dev/sdb: 2097152s
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start  End       Size      File system  Name     Flags
 1      2048s  2095103s  2093056s               primary

tuning nginx compression and decompression

Much of what NGINX has configured for us by default is great, but there are some settings that we can adjust to make the server perform even better. One of the adjustments that we can make is to have NGINX compress resources before sending them to the client. This modification isn’t free, as it does add some CPU overhead, but not enough to outweigh the benefits.
Note: the commands in this video are run as the root user.

Documentation For This Video

Configuring and Enabling GZIP

We came across gzip when we first installed NGINX and looked at the default configuration, but it was commented out. The simplest way to enable compression for our responses is to uncomment that line in our nginx.conf file:
/etc/nginx/nginx.conf (partial)
    gzip on;
That change is simple enough, but there’s more that we can do to make this better by using some of the other directives from the gzip module. By default, we’re not going to compress the responses that we’re getting from proxied servers or any piece of content that isn’t HTML. Let’s make some modifications to compress more of what we know we’ll respond with:
/etc/nginx/nginx.conf (partial)
  gzip on;
  gzip_disable msie6;
  gzip_proxied no-cache no-store private expired auth;
  gzip_types text/plain text/css application/x-javascript application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon image/bmp image/svg+xml;
  gzip_min_length 1024;
  gzip_vary on;
Let’s break down these directives:
  • gzip_disable - Ensure that we’re not sending compressed responses to older versions of Internet Explorer (hopefully no one is actually using these browsers)
  • gzip_proxied - Specify that we only want to compress responses from proxied servers if we normally wouldn’t cache them
  • gzip_types - The Content-Types that we will compress before sending the response
  • gzip_min_length - Adjusting the minimum size of a file that we’ll compress, the default is 20 bytes, but we’re going to not compress resources that are less than one kilobyte
  • gzip_vary - Adds a Vary: Accept-Encoding header. This tells intermediate caches (like CDNs) to treat the compressed and uncompressed version of the same resource as 2 separate entities

What About Decompression

We’re handling on-the-fly compression now, but if one of our proxied servers happens to send us a pre-compressed response then we probably want to decompress it for clients that can’t handle gzip. In this situation, we’ll use the gunzip module, and we’ll place this in the same area as our gzip directives:
/etc/nginx/nginx.conf

  gzip on;
  gzip_disable msie6;
  gzip_proxied no-cache no-store private expired auth;
  gzip_types text/plain text/css application/x-javascript application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon image/bmp image/svg+xml;
  gzip_min_length 1024;
  gzip_vary on;
  gunzip on;

improve ssl config in nginx

Improving SSL Configuration with SSL Session Caching

Up to this point, when we’ve worked with SSL in our servers, we’ve done the bare minimum by using ssl_certificate and ssl_certificate_key. There are a number of other settings that we can and should set to improve the overall configuration. These improvements are better for security, but can also improve our server performance by alleviating repetitive work.
To begin, let’s add session caching so that fewer SSL handshakes need to be made. The initial handshake is the most taxing part of the process, and if we can avoid repeating it then we’ll improve our overall performance. Let’s make some changes to our /etc/nginx/conf.d/default.conf file to add SSL session caching.
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
These three new directives do the following:
  • ssl_session_timeout - set’s how long a session can persist
  • ssl_session_cache - set’s the number of sessions to cache. The shared value indicates that it can be used by all NGINX processes. One megabyte of space can hold about 4,000 sessions
  • ssl_sessions_tickets - SSL Tickets are an idea where encrypted session information is stored on the client instead of the server. We’re opting to not use tickets

Setting SSL Cipher and Protocols

Depending on the clients that will be interacting with a service, the configuration of the TLS protocols and ciphers can be important. For our purposes, we’re expecting that our clients are using modern web browsers (at least IE 11, FireFox 27, Chrome 30, Safari 9, or Android 8). Knowing that we expect “modern” clients we’ll set some values based on suggestions from Mozilla.
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;
Note: You can read about these suggestions and more about backward compatibility here.
We know that all of our clients can work with TLS version 1.2 so we’re going to require it using ssl_protocols. Skipping over the ciphers for a moment, we’re setting ssl_prefer_server_ciphers so that we utilize the list of ciphers that we specify rather than using client ciphers. This configuration is so that our server is in control of the SSL/TLS experience, so we’re keeping as much as we can under the server’s umbrella. The ssl_ciphers list is quite long, the ordering is important, and we’re not (at least I’m not) cryptography experts. This list is taken directly from Mozilla as recommended.

HSTS and OCSP Stapling

We only have a few more things to change. The first is adding support for HSTS. HSTS is a way to have NGINX tell the client that it should never interact with our domain using HTTP, and we add this using a header. If we were not ready for our domain/IP address to only receive HTTPS traffic then we should NOT add this header until we are:
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

    # 15768000 is roughly 6 months
    add_header Strict-Transport-Security max-age=15768000;
Now any browser that receives a response from our server will refuse to send traffic over HTTP to our domain for the duration of max-age.
Our last change relates to OCSP or “Online Certificate Status Protocol”. Without OCSP stapling, the client will need to make a separate request to verify the validity of a certificate from the issuer, but with OSCP stapling, the server can make that request and cache it for awhile to return that information with the initial handshake. Let’s add OCSP Stapling:
/etc/nginx/conf.d/default.conf (partial)
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

    # 15768000 is roughly 6 months
    add_header Strict-Transport-Security max-age=15768000;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
If we check our configuration using nginx -t, we’ll see that we have a warning related to OCSP stapling:
nginx: [warn] "ssl_stapling" ignored, issuer certificate not found for certificate "/etc/nginx/ssl/public.pem"
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Since we’re using a self-signed certificate, the stapling is ineffective. In a setting where we’re using a certificate from an actual certificate authority, we would also want to include the following directive with a downloaded root CA certificate:
/etc/nginx/conf.d/default.conf (partial)
  ssl_trusted_certificate /path/to/ROOT_CA_CERT;

When we discuss using Let’s Encrypt, we’ll generate a valid and verifiable certificate. At that point, we’ll be able to revisit OCSP stapling.

nginx microcaching


we’ll look at an alternative caching strategy that is useful if you have an application with dynamic content that is receiving a lot of traffic.
Note: the commands in this video are run as the root user.

Documentation For This Video

What is “Microcaching”?

If an application or website is updated very frequently, then caching becomes pretty difficult because you don’t know when to remove the cache. If that same application receives a lot of traffic then routing all of that traffic to the application server can overwhelm the server quite quickly. NGINX is good at responding to a lot of traffic, and if the content of the website doesn’t always need to be updated in real-time, then microcaching might be worth using. This is where “microcaching” comes into play. With microcaching, we’re going to cache the contents of requests for just a few seconds, and for the same content, we’ll only send one request every 10 seconds or so to the application server.

Implementing Microcaching

To demonstrate microcaching, we’re going to add it to our UWSGI application and then send a lot of traffic to it. Before we add the caching, let’s install [boom] and see how our application handles a large spike in traffic.
[root] $ pip install boom
With boom installed, we’ll send traffic to https://notes.example.com:
[root] $ boom http://localhost/ --header Host:notes.example.com -c 30 -n 3000
Server Software: nginx/1.12.2
Running GET http://127.0.0.1:80/
        Host: notes.example.com
Running 3000 queries - concurrency 30
[================================================================>.] 99% Done

-------- Results --------
Successful calls                3000
Total time                      15.1118 s
Average                         0.1503 s
Fastest                         0.0444 s
Slowest                         0.1600 s
Amplitude                       0.1157 s
Standard deviation              0.006783
RPS                             198
BSI                             Pretty good

-------- Status codes --------
Code 200                        3000 times.

-------- Legend --------
RPS: Request Per Second
BSI: Boom Speed Index
Sending 3000 total requests using 30 concurrent users 15 seconds. That performance is bad really, but let’s modify the configuration for notes.example.com to see if NGINX can make a difference for us without aggressively caching content like we did for the blog:
/etc/nginx/conf.d/notes.example.com.conf
uwsgi_cache_path /var/cache/nginx/micro levels=1:2
                 keys_zone=micro:10m max_size=1g;

server {
    listen 80;
    server_name notes.example.com;

    uwsgi_cache_key $scheme$request_method$host$request_uri;

    location /static {
        root /var/www/notes.example.com;
    }

    location / {
        add_header X-Cache-Status $upstream_cache_status;
        include uwsgi_params;
        uwsgi_pass unix:/var/run/uwsgi/notes.sock;
        uwsgi_cache micro;
        uwsgi_cache_valid 10s;
    }
}
The main difference between this configuration and the cache we set for the blog is with this line:
uwsgi_cache_valid 10s;
This means we’re only caching content for 10 seconds. Since our original result took more than 10 seconds, we should be able to see a noticeable difference running the same load test. Let’s see what kind of difference the microcaching gives us:
boom http://localhost/ --header Host:notes.example.com -c 30 -n 3000
Server Software: nginx/1.12.2
Running GET http://127.0.0.1:80/
        Host: notes.example.com
Running 3000 queries - concurrency 30
[================================================================>.] 99% Done

-------- Results --------
Successful calls                3000
Total time                      6.4929 s
Average                         0.0595 s
Fastest                         0.0200 s
Slowest                         0.0808 s
Amplitude                       0.0608 s
Standard deviation              0.004789
RPS                             462
BSI                             Pretty good

-------- Status codes --------
Code 200                        3000 times.

-------- Legend --------
RPS: Request Per Second
BSI: Boom Speed Index
Our Requests Per Second (RPS) went from 198 to 462! That’s a huge increase in performance without needing to worry about returning stale content for a long period of time like we potentially could with more aggressive caching.
Knowing how long to cache information is a pretty hard problem to solve. If we have an application that doesn’t deploy very often or that doesn’t display that much dynamic data, then we can be aggressive with caching setting a longer cache_valid time. Microcaching is a good alternative to get some more performance out of your application servers when you do have dynamic content that is allowed to be stale for a short period of time.