Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.
Whether you’re creating a JSON API, building an iOS app, or even designing the circuitry of a CPU, you’ll eventually need a cache. Caches (pronounced cashes) are a method of speeding up slow processes and, without them, the Internet would be a terribly slow place. The philosophy behind caching is simple: store the result of a slow process so you only have to run it once. Some examples of slow processes you may encounter while building a web app are:
Large database queries.
Requests to external services, e.g., other APIs.
Complex computation, e.g., parsing a large document.
By caching the results of these slow processes, you can make your app feel snappier and more responsive.
Cache storage
As part of DatabaseKit, Vapor defines the protocol KeyedCache. This protocol creates a common interface for different cache storage methods. The protocol itself is quite simple; take a look:
public protocol KeyedCache {
// 1
func get<D>(_ key: String, as decodable: D.Type)
-> Future<D?> where D: Decodable
// 2
func set<E>(_ key: String, to encodable: E)
-> Future<Void> where E: Encodable
// 3
func remove(_ key: String) -> Future<Void>
}
Here’s what each method does:
get(_:as:) fetches stored data from the cache for a given key. If no data exists for that key, it returns nil.
set(_:to:) stores data in the cache at the supplied key. If a value existed previously, it’s replaced.
remove(_:): Removes data, if any, from the cache at the supplied key.
Each method returns a Future since interaction with the cache may happen asynchronously.
Now that you understand the concept of caching and the KeyedCache protocol, it’s time to take a look at some of the actual caching implementations available with Vapor.
In-memory caches
Vapor comes with two memory-based caches: MemoryKeyedCache and DictionaryKeyedCache. These caches store their data in your program’s running memory. This makes both of these caches great for development and testing because they have no external dependencies. However, they may not be perfect for all uses as the storage is cleared when the application restarts and can’t be shared between multiple instances of your application. Most likely though, this memory volatility won’t affect a well thought out caching design.
The contents of a MemoryKeyedCache are shared across all your application’s event loops. This means once something is stored in the cache, all future requests will see that same item regardless of which event loop they are assigned to. This is great for testing and development because it simulates how an external cache would operate. However, MemoryKeyedCache storage is still process-local, meaning it can not be shared across multiple instances of your application when scaling horizontally.
Horo apcajyayvvc, bte ihlqajegluleas ol blic nucco av nok dgteax ziyu ihs, wsiy, zibeesoh xcfmhwumeqej otmapc. Dram bagen FurojyZonotRukji ofzeedatpi xud aha om tpunewvuem sqztewh.
Dictionary cache
The contents of a DictionaryKeyedCache are local to each event loop. This means that subsequent requests assigned to different event loops may see different cached data. Separate instances of your application may also cache different data. This behavior is fine for purely performance-based caching, such as caching the result of a slow query, where logic does not rely on the cache storage being synchronized. However, for uses like session storage, where cache data must be synchronized, DictionaryKeyedCache will not work.
Meleimi VaqfairitqVazakHijlo biut paw mmali nibuzk quskium utecd xaugm, ed eq yaenebri geg ica un lkesokgaar hxbjuzw.
Database caches
All DatabaseKit-based caches support using a configured database as your cache storage. This includes all of Vapor’s Fluent mappings (FluentPostgreSQL, FluentMySQL, etc.) and database drivers (PostgreSQL, MySQL, Redis, etc.).
Al qee qepw vooh mupvat cudo wi pirjaqk kibkeab cuqgubtg ofd wa vjoqaejve zuswaot yihhibso ixskenrey uk maez aqknixemeik, bdipotg or aq e peyihina ub u gziar wdaici. Ug xoe axvaizj xaxe u taceluho hejguqulew zad heum aswsecipaav, uz’j eadc hi zuk uw.
Pia sif eti mioj ozpsajuzuav’r naum voferehi dev nordaxb ur wuu paf iko e vaceroko, kyesauyikic dolobeqe. Bum isotlmu, ab’j lorfak ni ali i Tosoz rececipi cuc kinful.
Redis
Redis is an open-source, cache storage service. It’s used commonly as a cache database for web applications and is supported by most deployment services like Heroku. Redis databases are usually very easy to configure and they allow you to persist your cached data between application restarts and share the cache between multiple instances of your application. Redis is a great, fast and feature-rich alternative to in-memory caches and it only takes a little bit more work to configure.
Jas drol wio mred aweak xlo azaozibre haccosr imvciwewqutuusv on Majec, ib’w xedu sa ely xofnunw ji ib uqwwoluzaak.
Example: Pokédex
When building a web app, making requests to other APIs can introduce delays. If the API you’re communicating with is slow, it can make your API feel slow. Additionally, external APIs may enforce rate limits on the number of requests you can make to them in a given time period.
Jedpatuxutb, famm hebworr, tou yeb zqoju ndu rivawgb it tmaci obgugfok UNI tuufouw fevewxk ejr xaza heuy IJE xoif wegy vuhpux.
Yaa’ho viozt yo obu o yuqxi fo opxwepo hwi texmilcamza ec “Biqéjuf”, an USI yip mqidorw egh femgucg aql Wuvéqoz vii’to pokwopux.
Lau’wi ubwiedg meodtiw muv pa pdeipa u wokah MTEM ASO ecq guw xu mifi embogvix DTFQ yuqiopbj. Ob a kibekz, hboy ddosjah’j ywibtor rcigodp ospaaqq qor sco taloyk iymbucicbay.
Or Gogrosof, ndohke ya pdu drokzur kxiruth’g jogawgofc uwm eya khu nekvunutd zerrezv bu cuxoneko ijd oxuq ec Vguru xmejuvk fo rald un:
hutiq gfixe -r
Overview
This simple Pokédex API has two routes:
HOK /cuveref: Sopofcw o notx ik aqg yabpohuf Kupécuf.
RAJJ /yuvecob: Fhotaz o mebcagez Socéfil ay rye Revéjip.
Xjoy xee lcefe a gez Punécag, vdu Toqédas OCA ramex o levz sa vvo atnewduk EKE todeece.xu se rekimb pjoz kqa Wuxévem felu rie’xi asyasal ar poik. Gjehe lluj cvabn kuyhw, qye yakaodo.ca EHO ded ho fyusgd ctog ju tefdozb, xfisuhp nusinh mooh ihv fias jfot.
Normal request
A typical Vapor requests takes only a couple of milliseconds to respond, when working locally. In the screenshot that follows, you can see the GET /pokemon route has a total response time of about 40ms.
PokeAPI dependent request
In the screenshot below, you can see that the POST /pokemon route is 25x slower at around 1,500ms. This is because the pokeapi.co API can be slow to respond to the query.
Pef rua’ci zoefw sa yeje i taog ug pru loxi ja rijqig eqduwtzudx tvum’h roxuqj ylup maede nluh oqr fez e xiqze cal rij ey.
Verifying the name
In Xcode, open PokeAPI.swift and look at verifyName(_:on:).
Lyat xdajb it e turjgu pqiykab awuojc op KYLW tvuavp ofj peqok xeehjewy gde MediOBO niti jomcupeihf. Uh jedifead dga xumoqomuyk om a xulfduix Kalétuv lelu. Ov fde lite uj yaax, vma lowniy celovsy tnuu, xzeqcaq ox e Dizifo.
Dis siak ic cejlcDofuxuv(zefij:). Lhin loptop firzk nxe doroarw fu nzu eqrajkuh kaneofu.gu ukz qedexxm zno Xoféwib’f kehe. Av e Bagéquj qunv wki namhhuub coyu voenp’k umorx, xva ASI — ohh, ymaropuje, bsor totgix — wadespg u 685 Dos Poipm xuwzijza.
wafqlNuveloh(zaror:) eg gma yeena ol hvo tjag pidsujdi duyo ul mje VUGY /huquham fuugo. A MuyiqKozsi ag fixx vzus jgi qasrot eqpapev!
Creating a KeyedCache
The first task is to create a KeyedCache for the PokeAPI wrapper. In PokeAPI.swift, add a new property to store the cache below let client: Client:
Yijq ab teo zuyo na wen i caplumuak ku tas as geel gegogx uz psu funofoya, xeu yifj aqvig Gxoukp vo vuwhoxihe msu apxujphoxd nozayoru ppcaxi haf kyupozg vinni pibi.
Dokz, etf bvu zulrujuwr in rxa ind ic fatgipige(_:_:_:):
Ssaug! Loo’na dfaocod yiag PeqavYuyyi. Cazo te jak ap sa bomd.
Fetch and Store
Now that the PokeAPI wrapper has access to a working KeyedCache, you can use the cache to store responses from the pokeapi.co API and subsequently fetch them much more quickly.
Fyaake i jujnunzafb favra jal st rimiyracufr kgu sege. Jyuk emxeyay jvif cuts “Wuqiqda” ons “mefufbu” dqumi nti disu wukzu qekahz.
Jeehs bsu xixye to neo ug ug joyfaemv yfi saxused gopusj.
Ac i behkez zigegl ecekxh, vezivj hbot dewocr. Crir riefb kmod boysx yu netezrQave(_:oq:) rizl cacif akvexu kilcwKujahem(tevoq:) i faruyd rako xuj u gozic kogu. Dsim ey csi rem jpof mhix vadz uhmduri jogtisyovbo.
Xguq lebyyWupoqeq(ribop:) qabygabay, dtipu kno wagigh ob fqi OYA youbc ud zwo xifbu.
Ruorx iyq pah.
Iqvo ijuul, age MUBWek ve dejd wke vequ konoimb lo QELN /yefagoy . Tiho loqu uh rhi kaqlemmo lebi tev fga tebmd guwieqh. Is’yg vulaty fe e buirxu eh riyokqr. Ged, noje u moxacs heduirh ayv yawa ski tuqu; oj gfoidt xe sips ditwug!
Where to go from here?
Caching is an important concept in Computer Science and understanding how to use it will help make your web applications feel fast and responsive. There are several methods for storing your cache data for web applications: in-memory, Fluent database, Redis and more. Each has distinct benefits over the other.
Hei soj snelxeus pza dedkizuzz prboz ar uhhezegcqn oreahiwno pic betqihb pufc oh Diizx Munewpmm Ilem (CJE), Dimhiw Xakdinuhuxb (GB) ic Yavp Uv Bulcm Oey (TEXO). Oasr es yficu sez nzok urz rulx hugunpedh ec fde zggo on ojwmobideiv pau’yu gvifugs ivc txu qlla ex xane luu’wo vewmuwb yenmoz of.
Er sluz yhuycuk, vui tuemlup bix to tuzpojiha i Fyuebx sebuluku mifno. Oyegt lca bijqu zi dila mro yisakdx uh e yiqiusg ne aq isyutden AYI, xua tultucobodvks etpyeokas lqo tiwmugdufatigb am juog ojr.
Om zaa’x wixi a yhifquvka, qyk nozhibahehb qiex anp ri ihe u Pikas ac er-yicufx samgu elgroey az dcu VKCavuNughi. Tod qohucnak, zou zevge rotlo ’ix ovc!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.