CL-HTTP Chapter 9: Data Caching and Performance


Reference Manual | Prev: Chapter 8. Authentication | Next: Chapter 10. HTTP Client


Contents

  1. 9.1 Data Cache
  2. 9.2 Expiration and Cache-Control
  3. 9.3 Conditional GET
  4. 9.4 Resource Pooling
  5. 9.5 Performance Guidelines
  6. 9.6 Logging

9.1 Data Cache

CL-HTTP provides an in-memory data caching facility that stores response bodies in dynamic memory for fast serving. The data cache avoids repeated disk access for frequently requested static files by maintaining their contents in RAM. The implementation is in http:server;data-cache.lisp.

9.1.1 Data Universes

The data cache is organized around data universes — named collections of cached data. Each universe maintains a hash table of cached entries, tracks total cache size, and supports asynchronous revalidation of stale entries. The class hierarchy is:

The variable http:*standard-data-universe* holds the current data universe object.

;; Intern a data universe, creating it if necessary
(http::intern-data-universe "My-Cache"
                            :if-does-not-exist :create
                            :class 'http::file-data-universe)

9.1.2 Caching Data

The generic function cache-data is the primary method for caching data sources in a universe:

(cache-data universe data-source
            &key revalidation-interval wired-p)

When data-source is a pathname, the system creates the appropriate cache object — either a crlf-file-data-cache for text files that need CRLF canonicalization, or a binary-file-data-cache for binary files. The :wired-p keyword prevents the cached data from being evicted under memory pressure.

9.1.3 The define-cached-data Macro

The define-cached-data macro provides a declarative interface for specifying the initial data to cache in a universe:

(http::define-cached-data ("Standard-Pathname-Cache"
                           :audit-access-p t)
  ;; Wire frequently accessed files into the cache
  ("http:www;cl-http;cl-http.html" :wired-p t)
  "http:www;cl-http;icons;power.gif")
:clear-data-universe-p (default t)
Controls whether existing universes are cleared before caching.
:audit-access-p
Controls whether the universe tracks accesses of uncached data, useful for identifying candidates for caching.
:data-universe-class (default 'file-data-universe)
The class of universe to create.

9.1.4 Revalidation

The file-data-universe class supports asynchronous revalidation. A background process periodically checks cached files against disk, refreshing any whose modification dates have changed. The revalidation interval is controlled per-universe and per-cache-entry. Revalidation avoids serving stale content without incurring the cost of checking disk on every request.


9.2 Expiration and Cache-Control

CL-HTTP supports HTTP expiration headers that control how downstream caches (proxies and browsers) handle cached copies. Expiration is configured per-URL via the :expiration keyword on http:export-url.

9.2.1 Expiration Types

The :expiration argument takes a list whose first element specifies the type:

:no-expiration-header
No Expires header is issued. Caching behavior is left to the client's discretion.
:never
Issues an Expires header indicating one year from now, effectively marking the resource as permanently cacheable.
:time universal-time
Issues an Expires header for the specified absolute universal time.
:interval seconds
Issues an Expires header computed as the current time plus the interval in seconds. This is the most common form.
:function function
Calls function with the URL object. The function should return a universal time for the Expires header, or nil to suppress the header.
;; Content expires in one hour
(http:export-url #u"/reports/daily.html"
                 :computed
                 :response-function #'write-daily-report
                 :expiration '(:interval 3600))

;; Content expires at a specific time
(http:export-url #u"/events/schedule.html"
                 :html-file
                 :pathname "http:www;events;schedule.html"
                 :expiration '(:time 3980000000))

;; Content never expires (one year)
(http:export-url #u"/static/logo.gif"
                 :gif-image
                 :pathname "http:www;images;logo.gif"
                 :expiration '(:never))

9.2.2 Cache-Control Directives

HTTP/1.1 cache-control headers provide finer-grained control than Expires. The :cache-control keyword on http:with-successful-response and http:with-conditional-get-response accepts a property list of cache-control directives:

(http:with-successful-response (stream :html
    :cache-control '(:public t :max-age 3600))
  (html:with-html-document (:stream stream)
    ...))

9.3 Conditional GET

Conditional GET allows a client to validate its cached copy of a resource without transferring the full response body. CL-HTTP implements this via the with-conditional-get-response macro.

9.3.1 with-conditional-get-response

(http:with-conditional-get-response
    (stream content-type
     &key bytes last-modification character-set
          entity-tag expires location cache-control
          content-location content-language
          additional-headers additional-mime-headers
          termination-line-p version)
  body)

This macro checks whether the client has provided an If-Modified-Since header. If the resource has not been modified since that time, the server returns a 304 Not Modified response with updated headers but no body. Otherwise, body is executed and the full response is sent.

(defun write-data-page (url stream)
  (let ((last-mod (get-data-modification-time)))
    (http:with-conditional-get-response
        (stream :html
         :last-modification last-mod
         :expires (+ (get-universal-time) 3600)
         :cache-control '(:public t))
      (html:with-html-document (:stream stream)
        (html:with-document-preamble (:stream stream)
          (html:declare-title "Data Report" :stream stream))
        (html:with-document-body (:stream stream)
          (write-report-body stream))))))

9.3.2 Entity Tags

Entity tags (ETags) provide a more reliable validation mechanism than modification dates, especially for content that may change within the resolution of the file system clock. Supply the :entity-tag keyword (or :version, which maps to entity-tag) to enable ETag-based conditional responses.


9.4 Resource Pooling

The resource pooling facility (in http:mcl;server;resources.lisp) provides object reuse to reduce garbage collection pressure. Rather than allocating and discarding objects on every request, pooled objects are returned to a free list and reused. CL-HTTP pools buffers, server objects, process objects, and HTTP connections.

9.4.1 defresource

(defresource name (parameters)
  :constructor constructor-function
  :initializer initializer-function
  :deinitializer deinitializer-function
  :initial-copies count
  :matcher predicate)
:constructor
A function called to create a new object when the pool is empty. Receives the resource object and the parameters as arguments.
:initializer
Called on a newly allocated object (whether freshly created or reused from the pool) with the parameters. Prepares the object for use.
:deinitializer
Called when an object is returned to the pool. Clears references to allow garbage collection of objects the resource refers to.
:initial-copies
Number of objects to pre-allocate when the resource is defined.
:matcher
A predicate that tests whether an unallocated pool object is suitable for a particular allocation request. Useful when the pool contains objects of varying sizes.

9.4.2 Allocating and Deallocating

;; Manual allocation and deallocation
(let ((buffer (allocate-resource 'http-buffer 8192)))
  (unwind-protect
      (process-with-buffer buffer)
    (deallocate-resource 'http-buffer buffer)))

;; Automatic with using-resource
(using-resource (buffer http-buffer 8192)
  (process-with-buffer buffer))

The using-resource macro is the preferred interface. It allocates an object from the named resource, binds it to the variable, executes the body, and deallocates the object on exit (including non-local exits via unwind-protect).

9.4.3 Standard Resources

CL-HTTP defines several standard resources:


9.5 Performance Guidelines

CL-HTTP has been designed to run efficiently while preserving abstractions that enhance intelligibility and extensibility. The following guidelines help you write response functions and application code that runs fast without sacrificing the power of Common Lisp.

9.5.1 Algorithmic Efficiency

Come up with efficient algorithms (logarithmic or better) before micro-optimizing. Start by developing good abstractions, then optimize only the critical path. Meter your code using the Common Lisp time function and profiling tools — this is the only way to find out where time is actually spent.

9.5.2 Minimize Consing

Minimize unnecessary consing by using destructive operations (nconc, nreverse, delete) and copying data structures only when necessary. Use the dynamic-extent declaration to stack-allocate temporary data and closures:

;; Stack-allocate the closure for mapping
(flet ((process-header (name value)
         (write-header-to-log name value log-stream)))
  (declare (dynamic-extent #'process-header))
  (map-headers #'process-header))

Prefer flet local functions over anonymous lambda expressions — named local functions allow the closure to be consed on the stack rather than the heap. When mapping over sequences, either pass all arguments explicitly or use a named flet with dynamic-extent declared.

9.5.3 Avoid FORMAT in Hot Paths

format incurs overhead parsing the control string. In inner loops and response-generation hot paths, use write-string, write-char, and princ directly:

;; Slow: FORMAT parses the control string each time
(format stream "~A: ~A~%" name value)

;; Fast: direct output operations
(write-string name stream)
(write-string ": " stream)
(princ value stream)
(terpri stream)

9.5.4 Inline Critical-Path Functions

Use declaim inline for small functions on the critical path. This conserves abstraction while gaining efficiency. Beware of over-inlining that bloats the instruction cache working set. Metering determines when inlining is appropriate.

9.5.5 Minimize Keyword Arguments

Keyword argument processing has runtime overhead. In frequently called functions (but not macros or inline functions), prefer positional arguments. Keep the number of arguments to inner-loop functions to four or fewer for efficient register passing. Pass positional :start and :end arguments to sequence operations when available in the local context.

9.5.6 Use LOOP Iteration Paths

Use the loop iteration macro and especially the iteration paths (collect, append, nconc) because these expand into very efficient code.

9.5.7 Use Resources to Recycle Data Structures

Use defresource pooling (see Section 9.4) to recycle data structures rather than consing new ones, unless the allocation/deallocation overhead is more expensive than merely creating new structures each time.

9.5.8 Avoid Serializing Threads

Do not serialize threads responding to requests because of a shared resource. Use fine-grained locking, lock-free patterns, or per-thread state to maintain concurrency. The data cache uses multiple-reader-single-writer locks to allow concurrent read access.

9.5.9 Minimize Generic Function Calls

Use generic functions at points where method specialization enhances abstraction, and otherwise use functions and fast slot accessors. In some implementations, with-slots and slot-value are faster than generic function accessors.

9.5.10 Declare Numeric Types

Declare all numeric operations to avoid bignum arithmetic:

(let ((count 0))
  (declare (type fixnum count))
  (loop for item in items
        do (incf count))
  count)

9.6 Logging

CL-HTTP provides a modular logging system based on CLOS mixin classes. Log objects are composed from mixins that provide different capabilities: file writing, counters, console notification, and dynamic per-URL tracking.

9.6.1 Log Classes

The standard log classes combine mixins for typical use cases:

http:common-file-log
Records accesses in Common Log Format (CLF), the standard web server log format. Includes counters and asynchronous file writing.
http:extended-common-file-log
Extends the Common Log Format with the Referer and User-Agent header fields. This is the default log class (http:*log-access-log-class*). Conses slightly more than common-file-log because it must copy two additional header values.
http:basic-common-file-log
Common Log Format without counters or notifications. Useful as an ancillary log.
http:http-log
Adds dynamic per-URL logging to the Common Log Format.

9.6.2 Log Mixins

The key mixin classes are:

http:basic-file-logging-mixin
Provides non-blocking file writing. On multi-threaded Lisps, log entries are written by a dedicated process via a task queue, so logging never blocks the HTTP connection.
http:log-counters-mixin
Tracks server statistics: request counts by method (GET, POST, HEAD, etc.), status code distribution, bytes transmitted and received, elapsed time, CPU time, and connection counts.
http:log-notification-mixin
Writes notifications to the log window (console).
http:compressed-file-logging-mixin
Automatically compresses log files when they are rolled over.

9.6.3 Configuring Logging

Set the default log class in your configuration file:

;; Use extended common log format (the default)
(setq http:*log-access-log-class* 'http:extended-common-file-log)

;; Install a log on a specific port
(http:intern-access-log "HTTP-8000-Log"
                        :port 8000
                        :class 'http:extended-common-file-log)

9.6.4 Custom Log Classes

To define a custom log class, subclass the appropriate mixins and provide methods for:

http:log-entry-writer
The non-blocking method that snapshots the state of an HTTP connection and returns a closure to write the entry to the log file.
http:write-access-log-entry
The blocking method that writes information to other streams.
(defclass my-custom-log
          (http:extended-common-file-format-mixin
           http:access-log
           http:basic-file-logging-mixin)
  ((log-file-name :initform "My-Log"
                  :allocation :class)))

(defmethod http:log-entry-writer
           ((log my-custom-log) (server http:server-logging-mixin))
  ;; Snapshot state and return a writer closure
  (let ((host (http::host-log-name server))
        (request (http:server-request server t)))
    (flet ((write-entry (log-stream)
             (format log-stream "~A ~A~%"
                     host request)))
      #'write-entry)))

9.6.5 Log Rotation

Log files are automatically rotated based on configuration. The method http::switch-log-file handles rotation, and the compressed-file-logging-mixin can automatically compress old log files.