Databases Reference
In-Depth Information
Thus, you should always run
getlasterror
with the
wtimeout
option set to a sensible
value for your application.
wtimeout
gives the number of milliseconds to wait for slaves
to report back and then fails. This example would wait 100 milliseconds:
> db.runCommand({"getlasterror" : 1, "w" : 2, "wtimeout" : 100})
Note that MongoDB applies replicated operations in order: if you do writes
A
,
B
, and
C
on the master, these will be replicated to the slave as
A
, then
B
, then
C
. Suppose you
have the situation pictured in
Figure 4-3
. If you do write
N
on master and call
getlasterror
, the slave must replicate writes
E
-
N
before
getlasterror
can report success.
Thus,
getlasterror
can significantly slow your application if you have slaves that are
behind.
Figure 4-3. A master's and slave's oplogs. The slave's oplog is 10 operations behind the master's.
Another issue is how to program your application to handle
getlasterror
timing out,
which is only a question that only you can answer. Obviously, if you are guaranteeing
replication to another server, this write is pretty important: what do you do if the write
succeeds locally, but fails to replicate to enough machines?
Tip #36: Don't use fsync on every write
If you have important data that you want to ensure makes it to the journal, you must
use the
fsync
option when you do a write.
fsync
waits for the next flush (that is, up to
100ms) for the data to be successfully written to the journal before returning success.
It is important to note that
fsync
does not immediately flush data to disk
, it just puts
your program on hold until the data has been flushed to disk. Thus, if you run
fsync
on every insert, you will only be able to do one insert per 100ms. This is about a zillion
times slower than MongoDB usually does inserts, so use
fsync
sparingly.
fsync
generally should only be used with journaling. Do not use it when journaling is
not enabled unless you're sure you know what you're doing. You can easily hose your
performance for absolutely no benefit.